简体   繁体   中英

RegExp constructor escapes slash character but not dot

Say I have this:

console.log(new RegExp('.git'));
console.log(new RegExp('scripts/npm'));

the results are:

/.git/
/scripts\/npm/

my question is - why does it escape the slash in scripts/npm, but it does not escape the . in .git? What is the rhyme and reason to that?

Note, in this case , the regex strings are being passed from the command line, so I need to convert them to regex using RegExp.

An unescaped / denotes the beginning and end of a regular expression. When you pass in a string containing / into the constructor, of course that / is part of the regular expression, not a symbol denoting the beginning or end.

The . is something else entirely, and has nothing to RE delimiters, so it's left as-is.

Note that if you want the regular expression to match a literal dot (rather than any character), you need to double-escape it when using the constructor:

console.log(new RegExp('\\.git'));

When you write regex in JS you can initialize regex strings using two / . This is called regular expression literal initialization. More about it here .

For instance

let re = /(\w+)\s(\w+)/;

Now, for the question why does it append \\ before / , it is simply due to the way RegExp processes the passed string literal. This prevents the passed string from becoming corrupt ensuring all passed characters are accounted. Furthermore if you examine the object returned by the RegExp , we can see that the actual source attribute is set to scripts\\\\/npm . So, the first \\ indicates literal significance of the second \\ . Whilst from regular expressions perspective \\ , it simply escapes the proceeding / to form regular expression literal notation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM