javascript - Why does "(" cause a regex not to match? -



javascript - Why does "(" cause a regex not to match? -

i have next string:

var foo = "{(y-7)}({x + d})" var find = "{(y-7)}"; var replacement = "12"; var re = new regexp(find, 'g'); foo = foo.replace(re, replacement);

but results in exact same string, without changes. but, if remove parens i.e "(" , ")" expression, seems work. why

why won't match when expressions contain "("?

characters have special meaning in regular look needs escaped. escape them putting backslash in front end of them, , set backslash in string need escape putting backslash in front end of it:

var find = "\\{\\(y-7\\)\\}";

(in situations characters doesn't need escaping in regular expression, because can understood without it, start escaping characters have special meaning, can read on exact situations not needed.)

demo:

class="snippet-code-js lang-js prettyprint-override">var foo = "{(y-7)}({x + d})" var find = "\\{\\(y-7\\)\\}"; var replacement = "12"; var re = new regexp(find, 'g'); foo = foo.replace(re, replacement); // show result in stackoverflow snippet document.write(foo);

javascript regex

Comments

Popular posts from this blog

php - How to pass multiple values from url -

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

database - php search bar when I press submit with nothing in the search bar it shows all the data -