JavaScript Regex, where to use escape characters?

You can use the regular expression syntax:

var programProductRegex = /[\s\/\)\(\w&-]/;

You use forward slashes to delimit the regex pattern.

If you use the RegExp object constructor you need to pass in a string. Because backslashes are special escape characters inside JavaScript strings and they’re also escape characters in regular expressions, you need to use two backslashes to do a regex escape inside a string. The equivalent code using a string would then be:

var programProductRegex  = new RegExp("[\\s\\/\\)\\(\\w&-]");

All the backslashes that were in the original regular expression need to be escaped in the string to be correctly interpreted as backslashes.

Of course the first option is better. The constructor is helpful when you obtain a string from somewhere and want to make a regular expression out of it.

var programProductRegex  = new RegExp(userInput);

Leave a Comment