2

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

3 Answers 3

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

1

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

1

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 Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.