为什么新的RegExp()字符串不需要转义正斜杠? [英] Why does new RegExp() string not require escaping a forward slash?

查看:73
本文介绍了为什么新的RegExp()字符串不需要转义正斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读此文档 https://developer.mozilla.org/zh-CN/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."

那么为什么RegExp()的这两种用法之间没有区别?

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.

推荐答案

正斜杠只是特殊字符,因为它们指定 literal 常规语法的开头和结尾用Java语言表达.但是,当您使用构造函数时,这不是必需的,因为提供给 new RegExp 的第一个参数是(整个)字符串,用于从中构造正则表达式.

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.

这篇关于为什么新的RegExp()字符串不需要转义正斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆