JavaScript: RegExp constructor and listing

I am learning RegExp, but everywhere I see two syntaxes

new RegExp("[abc]") 

and

 /[abc]/ 

And if with modifiers what is using an extra slash ( \ )

 /\[abc]/g 

I am not getting errors with these two, but I am wondering if there is a difference between the two. If so, what is it and what is the best way to use it?

I called Differences between Javascript regexp literal and constructor , but there I did not find an explanation of what is best and what is the difference.

+6
source share
3 answers

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

Suppose you want to combine 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 the literal /pattern/ , since everything that is between two slashes is interpreted literally.

Also note the need for double escape commands (i.e., \\ ) when specifying patterns this way, because we do this in a line - the first backslash must be escaped by the second, so one of them does it in the pattern. If there was only one, it would be interpreted by the JS parser as an escape character and be deleted.

+9
source
  • As you can see, the RegExp constructor syntax requires a line feed. \ in a line is used to exit the next character. Thus,

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

    will create a regular expression s .

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

    While /\s/ is the syntax of the letters, it will create a regular expression that is predictable.

  • RegExp constructor syntax allows you to dynamically create a regular expression.

So, when a regular expression needs to be created dynamically, use the RegExp constructor syntax; otherwise, use the regex literal syntax.

+6
source

There are two ways to define regular expressions.

  • Via the constructor of the object
    • May be changed at runtime.
  • Through a literal.
    • Compiled at boot script
    • Best performance

Literal is best used with well-known regular expressions, while the constructor is best suited for dynamically constructed regular expressions such as user input.

You can use either of the two, and they will be handled exactly the same.

0
source

All Articles