简体   繁体   中英

Why does new RegExp() string not require escaping a forward slash?

Reading this document https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

"When using the constructor function, the normal string escape rules (preceding special characters with \\ when included in a string) are necessary."

So why is there no difference between these two uses of RegExp()?

"a/b/c".match(new RegExp("\/", "g")) // (2) [ "/", "/" ]
"a/b/c".match(new RegExp("/", "g"))  // (2) [ "/", "/" ]

Is the document incorrect or am I missing something?

The possible duplicate question indicates that forward slashes must be escaped as literals. Using a string, the example above shows this is not the case given the use case of a string with the constructor function. This question is specifically about using a string with the constructor function.

So based on the answer below, the difference appears to be with literals, both the " and the / need to be escaped, but when using a string only the " needs to be escaped.

Forward slashes are only special characters in that they designate the syntactical beginning and end of a literal regular expression in Javascript. But when you use the constructor, that's not needed, because the first parameter provided to new RegExp is the (entire) string to construct the regular expression from.

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