[removed] RegExp constructor vs RegEx literal

2020-01-28 08:54发布

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

new RegExp("[abc]")

And

/[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?

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

3条回答
姐就是有狂的资本
2楼-- · 2020-01-28 09:39

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'));

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

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.

查看更多
beautiful°
3楼-- · 2020-01-28 09:40
  1. As you can see, the RegExp constructor syntax requires string to be passed. \ in the string is used to escape the following character. Thus,

    new RegExp("\s") // This gives the regex `/s/` since s is escaped.
    

    will produce the regex s.

    Note: to add modifiers/flags, pass the flags as second parameter to the constructor function.

    While, /\s/ - the literal syntax, will produce the regex which is predictable.

  2. The RegExp constructor syntax allows to create regular expression from the dynamically.

So, when the regex need to be crafted dynamically, use RegExp constructor syntax otherwise use regex literal syntax.

查看更多
放荡不羁爱自由
4楼-- · 2020-01-28 09:54

There are 2 ways of defining regular expressions.

  1. Through an object constructor
    • Can be changed at runtime.
  2. Through a literal.
    • Compiled at load of the script
    • Better performance

The literal is the best to use with known regular expressions, while the constructor is better for dynamically constructed regular expressions such as those from user input.

You could use any of the two and they will be handled in exactly the same way..

查看更多
登录 后发表回答