I would like to create a String.replaceAll() method in JavaScript and I'm thinking that using a regex would be most terse way to do it. However, I can't figure out how to pass a variable in to a regex. I can do this already which will replace all the instances of "B" with "A".
"ABABAB".replace(/B/g, "A"); But I want to do something like this:
String.prototype.replaceAll = function(replaceThis, withThis) { this.replace(/replaceThis/g, withThis); }; But obviously this will only replace the text "replaceThis"...so how do I pass this variable in to my regex string?
\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \. html?\ ' .
Instead of using the /regex\d/g syntax, you can construct a new RegExp object:
var replace = "regex\\d"; var re = new RegExp(replace,"g"); You can dynamically create regex objects this way. Then you will do:
"mystring1".replace(re, "newstring");
As Eric Wendelin mentioned, you can do something like this:
str1 = "pattern" var re = new RegExp(str1, "g"); "pattern matching .".replace(re, "regex"); This yields "regex matching .". However, it will fail if str1 is ".". You'd expect the result to be "pattern matching regex", replacing the period with "regex", but it'll turn out to be...
regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex This is because, although "." is a String, in the RegExp constructor it's still interpreted as a regular expression, meaning any non-line-break character, meaning every character in the string. For this purpose, the following function may be useful:
RegExp.quote = function(str) { return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); }; Then you can do:
str1 = "." var re = new RegExp(RegExp.quote(str1), "g"); "pattern matching .".replace(re, "regex"); yielding "pattern matching regex".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With