How to use variables in regular expressions?
P粉763748806
2023-08-23 15:12:16
<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>
As Eric Wendelin mentioned, you can do this:
This produces
"Regular expression match."
. However, it fails if str1 is"."
. You expected the result to be"Pattern Matching Regular Expression"
, replacing the periodwith
"Regular Expression", but the result would be...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:Then you can do this:
Produces
"pattern matching regular expression"
.You can construct a new RegExp object:
You can dynamically create regular expression objects this way. Then you would do: