JavaScript:RegExp构造函数与RegEx文字 [英] JavaScript: RegExp constructor vs RegEx literal

查看:123
本文介绍了JavaScript:RegExp构造函数与RegEx文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究RegExp,但到处都可以看到两种语法

I am studying about RegExp but everywhere I can see two syntax

new RegExp("[abc]")

/[abc]/

如果使用修饰符那么使用额外的斜杠( \

And if with modifiers then what is the use of additional slash (\)

/\[abc]/g

我没有得到这两个的任何错误,但我想知道这两个有什么区别。如果是,那么它是什么,最好使用哪个?

I am not getting any bug with these two but I wonder is there any difference between these two. If yes then what is it and which is best to use?

我提到了 Javascript regexp文字和构造函数之间的差异但是我没有找到哪个是最好的解释和什么是差异。

I referred Differences between Javascript regexp literal and constructor but there I didn't found explanation of which is best and what is difference.

推荐答案

关键区别在于文字REGEX不能接受动态输入,即来自变量,而构造函数可以,因为模式被指定为字符串。

The key difference is that literal REGEX can't accept dynamic input, i.e. from variables, whereas the constructor can, because the pattern is specified as a string.

假设您想匹配字符串中数组中的一个或多个单词:

Say you wanted to match one or more words from an array in a string:

var words = ['foo', 'bar', 'orange', 'platypus'];
var str = "Foo something nice orange what a lovely platypus";
str.match(new RegExp('\\b('+words.join('|')+')\\b'));

对于文字 / pattern / ,因为两个正斜杠之间的任何内容都按字面解释。

This would not be possible with a literal /pattern/, as anything between the two forward slashes is interpreted literally.

还需要双重转义(即 \\ )以这种方式指定模式时的特殊字符,因为我们在字符串中这样做 - 第一个反斜杠必须由第二个反转,因此其中一个使其成为模式。如果只有一个,它将被JS的字符串解析器解释为转义字符,并被删除。

Note also the need to double-escape (i.e. \\) special characters when specifying patterns in this way, because we're doing so in a string - the first backslash must be escaped by the second so one of them makes it into the pattern. If there were only one, it would be interpreted by JS's string parser as an escaping character, and removed.

这篇关于JavaScript:RegExp构造函数与RegEx文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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