Home  >  Q&A  >  body text

How to use variables in regular expressions?

<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粉763748806P粉763748806424 days ago574

reply all(2)I'll reply

  • P粉141455512

    P粉1414555122023-08-24 10:47:54

    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" .

    reply
    0
  • P粉318928159

    P粉3189281592023-08-24 10:01:04

    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");

    reply
    0
  • Cancelreply