JavaScript differences beetween new Regex('regex', 'flags') and /regex/flags

60 views Asked by At
var a = 'toto titi (should be removed) 5'.replace(/\(.*\)|\[.*\]|[^a-zA-Z0-9 ]|tata|tutu|tyty/gi, '!$!');
var b = 'toto titi (should be removed) 5'.replace(new RegExp('\(.*\)|\[.*\]|[^a-zA-Z0-9 ]|tata|tutu|tyty', 'gi'), '!$!');
console.log(a);
console.log(b);

I want to replace by space every char which is not a number or a letter or a space and chars which are beetween () and []. I have 2 same sentences, and I use the same pattern. The only one difference is that I use the /regex/flags syntax for var a and the object syntax new Regex('regex','flags') for var b.

However the result is not the same for a and for b.

Output is :

toto titi !$! 5 //a (it's the expected result)
!$!!$!          //b

I don't understand why. Could you explain me ? I have to use the object syntax because I need to build my regex with variables.

1

There are 1 answers

0
Scimonster On BEST ANSWER

In strings, a backslash (\) is used for escaping special characters, such as in \\, \', \". In a regex, backslashes are also used for escaping, such as a literal \( or \..

This means that when creating a regex from a string, you need to escape backslashes in the string as well. So you would do:

new RegExp('\\(.*\\)|\\[.*\\]|[^a-zA-Z0-9 ]|tata|tutu|tyty', 'gi')

Using this it gives the expected result.