admin管理员组

文章数量:1333442

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

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

Share Improve this question asked Feb 4, 2012 at 20:51 davejdavej 1,3805 gold badges17 silver badges35 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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

You need to escape the special characters contained in string you are creating your Regex from. For example, define this function:

function escapeRegex(string) {
  return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}

And use it to assign the result to your bad_string variable:

let bad_string = "bar(arg)"
bad_string = escapeRegex(bad_string)

// You can now use the string to create the Regex :v:

Your RegEx definition string should be:

var bad_string = "bar\\(arg\\)";

Special characters need to be escaped when using RegEx, and because you are building the RegEx in a string you need to escape your escape character :P

http://www.regular-expressions.info/characters.html

本文标签: javascripthow to config RegExp when string contains parenthesesStack Overflow