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+\)");
MDN Reference:
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 = new RegExp('^\(\d+\) ' + variable);
Escaping the slash is obligatory as it is itself is an escaping symbol.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…