JavaScript Regex, where to use escape characters?
Solution 1:
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);
Solution 2:
If you are using a String and want to escape characters like (
, you need to write \\(
(meaning writing backslash, then the opening parenthesis => escaping it).
If you are using the RegExp
object, you only need one backslash for each character (like \(
)
Solution 3:
Enclose your regex with delimiters:
var programProductRegex = /[\s\/)(\w&-]/;