Javascript正则表达式分隔符(正斜杠的任何替代)? [英] Javascript regex delimiters (any alternative to forward slash)?
问题描述
Javascript中是否有任何方法可以使用与 /
(正斜杠)不同的字符作为正则表达式中的分隔符?
大多数其他语言都可以这样做。
Is there any way in Javascript to use a different character than /
(forward slash) as a delimiter in a regular expression?
Most other languages have a way of doing this.
例如,Perl:
m@myregex@
我们是否仅限于使用/在Javascript中?
Are we confined to just using "/" in Javascript?
推荐答案
在JavaScript中使用正则表达式的简单方法中,您可以使用分隔它/
字符。但是,如果您想使用全局对象 RegExp
,然后你需要使用普通的字符串转义规则传入一个字符串作为构造函数的第一个参数。以下是等效的。
In the simple way of using regular expressions in JavaScript you would delimit it with the /
character. However, if you would like to use the global object RegExp
, then you would need to pass in a string as the first argument to the constructor using the normal string escape rules. The following are equivalent.
// shorthand way.
var re = /\w+/;
// a way to pass a string in
var re = new RegExp("\\w+");
这篇关于Javascript正则表达式分隔符(正斜杠的任何替代)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!