Search code examples
javascriptregexreplaceparentheses

how to config RegExp when string contains parentheses


I'm sure this is an easy one, but I can't find it on the net.

This code:

    var new_html = "foo and bar(arg)";
    var bad_string = "bar(arg)";
    var regex = new RegExp(bad_string, "igm");
    var bad_start = new_html.search(regex);

sets bad_start to -1 (not found). If I remove the (arg), it runs as expected (bad_start == 8). Is there something I can do to make the (very handy) "new Regexp" syntax work, or do I have to find another way? This example is trivial, but in the real app it would be doing global search and replace, so I need the regex and the "g". Or do I?

TIA


Solution

  • Escape the brackets by double back slashes \\. Try this.

        var new_html = "foo and bar(arg)";
        var bad_string = "bar\\(arg\\)";
        var regex = new RegExp(bad_string, "igm");
        var bad_start = new_html.search(regex);
    

    Demo