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
Post a Comment