Which Characters To Escape When Using Regexp Object In Javascript?
Solution 1:
When you do not use RegEx
, you can use a literal notation:
/^\(\d+\)/
But when you are using the RegEx constructor, you need to double escape these symbols:
var re = new RegExp("^\\(\\d+\\)");
There are 2 ways to create a RegExp object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks.
... Use literal notation when the regular expression will remain constant.
... Use the constructor function when you know the regular expression pattern will > be changing, or you don't know the pattern and are getting it from another source, such as user input.
Now, in case you have a variable, it is a good idea to stick to the constructor method.
var re = newRegExp('^\\(\\d+\\) ' + variable);
Escaping the slash is obligatory as it is itself is an escaping symbol.
Post a Comment for "Which Characters To Escape When Using Regexp Object In Javascript?"