Passing a String When a regexp is Expected

One last thing to note is that the four methods you just saw (split(), match(), search(), and replace()) can also take strings as opposed to regular expressions. In this case the string argument is used to produce a new regex as if it was passed to new RegExp().

Example of passing a string to replace:

"test".replace('t', 'r')

The above is the same as:

"test".replace(new RegExp('t'), 'r')

When you pass a string, you cannot set modifiers as you can with a normal constructor or regex literal.

Related Tutorial
Follow Us #