How to use variables in regular expressions?
P粉763748806
P粉763748806 2023-08-23 15:12:16
0
2
607
<p>I want to create a <code>String.replaceAll()</code> method in JavaScript and I think using regular expressions is the cleanest way. However, I don't know how to pass variables to the regular expression. I can already do this, replacing all instances of <code>"B"</code> with <code>"A"</code>. </p> <pre class="brush:php;toolbar:false;">"ABABAB".replace(/B/g, "A");</pre> <p>But I want to do something like this: </p> <pre class="brush:php;toolbar:false;">String.prototype.replaceAll = function(replaceThis, withThis) { this.replace(/replaceThis/g, withThis); };</pre> <p>But apparently this will only replace the text <code>"replaceThis"</code>... So how do I pass this variable into my regex string? </p>
P粉763748806
P粉763748806

reply all(2)
P粉141455512

As Eric Wendelin mentioned, you can do this:

str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");

This produces "Regular expression match." . However, it fails if str1 is ".". You expected the result to be "Pattern Matching Regular Expression", replacing the period with "Regular Expression", but the result would be...

regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex

This is because, although "." is a string, in the RegExp constructor it is still interpreted as a regular expression, representing any non-newline character, representing each character in the string character. For this purpose, the following functions may be useful:

RegExp.quote = function(str) {
     return str.replace(/([.?*+^$[\]\(){}|-])/g, "\");
 };

Then you can do this:

str1 = "."
var re = new RegExp(RegExp.quote(str1), "g");
"pattern matching .".replace(re, "regex");

Produces "pattern matching regular expression" .

P粉318928159

You can construct a new RegExp object:

var replace = "regex\d";
var re = new RegExp(replace,"g");

You can dynamically create regular expression objects this way. Then you would do:

"mystring1".replace(re, "newstring");
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template