Alternative to regexp $1 for replace - javascript

I am trying to modify a substring with .replace() in javascript.
Basically I want to put arbitrary text before and after the match.
var pattern = new RegExp("<div"+"(.*?)>", "g");
var text = "<div><div class='someClass'>"
text = text.replace(pattern, "<pre>"+"<div>"+ "$1" + ">" +"</pre>")
The code above changes text to:
"<pre><div>></pre><pre><div> class='someClass'></pre>"
Besides the extra ">>" this is correct, but it is ugly in the replace function.
How can I change my regex so I
Dont have to use $1 because it is not fully supported according to this
How can I change replace to something simpler like
text = text.replace(pattern, "<pre>"+ "THING_THAT_MATCHED" +"</pre>")

Use the following code:
var pattern = new RegExp("<div"+"(.*?)>", "g");
var text = "<div><div class='someClass'>"
text = text.replace(pattern, function(match, first_match) {
return "<pre>"+"<div>"+ first_match + ">" +"</pre>"
})
Also note that you code make your original code much neater, like so:
var pattern = new RegExp("<div"+"(.*?)>", "g");
var text = "<div><div class='someClass'>"
text = text.replace(pattern, "<pre><div>$1></pre>")

Related

Regex word search with apostrophe

highlightStr: function (body, searchString){
console.log(searchString);
var regex = new RegExp('(' + searchString + ')', 'gi');
console.log(regex)
return body.replace(regex, "<span class='text-highlight'>$1</span>");
}
Above is the code I'm using. I want to find and replace the searchString, which could be anything. It works fine for most words, but fails when finding words with apostrophes.
How can I modify the regex to include special characters like the appostrophe.
var body = "<br>I like that Appleā€™s.<br>";
var searchString = "Apple's";
Thank you
You should escape the search string to make sure the regex works OK even if the search string contains special regex metacharacters.
Besides, there is no need wrapping the whole pattern with a capturing group, you may always reference the whole match with $& placeholder from the replacement pattern.
Here is an example code:
var s = "I like that Apple's color";
var searchString = "Apple's";
var regex = new RegExp(searchString.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "gi");
document.body.innerHTML = s.replace(regex, '<b>$&</b>');

How to highlight text by using regex

I'm trying writing a script to help highlight when match with regex. Below is my example that what I do now.
var text = "SOMETHING ~WEIRDs~ AND Not WEIRD";
var regexp = /\b(WEIRD)\b/
var matches = text.match(regexp);
for (i = 0; i < matches.length; i++) {
var replace_all = RegExp(matches[i] + "(?![^<]*>|[^<>]*<\/)", "ig");
text = text.replace(eval(replace_all), "<span style='background- color:yellow'>" + matches[i] + "</span>");
}
console.log(text);
The output of the code above is
SOMETHING ~<span style='background- color:yellow'>WEIRD</span>s~ AND Not <span style='background- color:yellow'>WEIRD</span>
The output I want is
SOMETHING ~WEIRDs~ AND Not <span style='background- color:yellow'>WEIRD</span>
I would like to know is that anyway to write a regex contains regex and words provided? Or have any other method can solve this incorrect replace issue.
Your outer regex is fine. The issue is with the inner replace_all regex in the loop , as it replaces all instances of the found string, no matter its position in the original string.
Instead use the original Regex with replace() using the matches within the replacement string, like this:
var text = "SOMETHING ~WEIRDs~ AND Not WEIRD";
var regexp = /\b(WEIRD)\b/
var text = text.replace(regexp, '<span style="background-color: yellow">$1</span>');
console.log(text);
Also, as a general rule, never, ever use eval(). There is always a better solution or alternative.

Remove string between two variables

I have a string which has some data with a few special characters, Need to remove the data between the desired special char in JavaScript.
The special char would be obtained in a variable.
var desiredChar = "~0~";
And Imagine this to be the Input string:
~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~
So I'm supposed to remove the text in bold.
The desired output is supposed to be-
~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~
I've tried using "Replace" and "Regex", but as the desired character is being passed in a variable and keeps changing I'm facing difficulties.
You can create your own regex based on whatever the bounding character(s) are that contain the text you want removed, and then replace any text that matches that regex with a blank string "".
The JS below should work for your use case (and it should work for multiple occurrences as well):
var originalText = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
var desiredChar = "~0~";
var customRegex = new RegExp(desiredChar + ".*?" + desiredChar, "gi");
var processedText = originalText.replace(customRegex, "");
console.log(processedText);
You can build your regex from the constructor with a string input.
var desiredChar = "~0~";
// use the g flag in your regex if you want to remove all substrings between desiredChar
var myRegex = new Regex(desiredChar + ".*" + desiredChar, 'ig');
var testString = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
testString = testString.replace(myRegex, "");
Given input string you can use .indexOf(), .lastIndexOf() and .slice().
Note, OR character | passed to RegExp constructor should be escaped to avoid RegExp created by passing string interpreting | character as OR | within resulting RegExp passed to .replace().
var desiredChar = "~0~";
var str = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
var not = str.slice(str.indexOf(desiredChar), str.lastIndexOf(desiredChar) + desiredChar.length);
// escape OR `|`
var res = str.replace(new RegExp(not.replace(/[|]/g, "\\|")), "");
console.log(res)
You can use the RegExp object:
var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);
Then you can construct regexstring in any way you want.
You can read more about it at http://www.regular-expressions.info/javascript.html

Search and Replace with JS: RegExp that does not include html code

I'm looking for a regexp that matches to strings in html body but does not influence strings that appear in title tags e.g. I have:
words = new Array("Android","iOS");
change = new Array ("http://www.google.com","http://www.apple.com");
obj = document.getElementsByTagName("body")[0];
// search and replace
for (i in words) {
re = new RegExp("\\b("+words[i]+")\\b", "ig");
str = obj.innerHTML.replace(re,'$1');
document.getElementsByTagName("body")[0].innerHTML = str;
}
}
So I have a list with words an the JS is replacing these words (eg replacing iOS' by <a href='http://www.apple.com'>iOS</a>) from HTML Body. But: it also replaces HTML Code like '<title = 'iOS'> -> this becomes <title='a href='http://www.apple.com'>iOS</a>' . How can the regexp can be changed that <title='...> and stuff are not changed
Adam
Use a look-ahead to ensure the target is not within a tag (ie the next angle bracket is a <):
re = new RegExp("\\b(" + words[i] + ")\\b(?=[^>]*<)", "ig");

Javascript replace does not replace

The pattern in this code does not replace the parenthesis. I've also tried "/(|)/g".
var re = "/[^a-z]/g",
txt = navsel.options[i].text.split(" ")[0], // here I get the text from a select and I split it.
// What I expect is strings like "(en)" , "(el)" etc
txt = txt.replace(re," ")
Thanks in advance
Your regex is a string, this will try to replace that exact string. Regex objects don't have quotes around them, just the delimiters. Try it like this:
var re = /[^a-z]/g,
txt = navsel.options[i].text.split(" ")[0], // here I get the text from a select and I split it.
txt = txt.replace(re," ");
Or if you prefer strings (and a more explicit type):
var re = new RegExp("[^a-z]", "g")

Categories

Resources