JavaScript Regex, where to use escape characters?

The regex allows chars that are: alphanumeric, space, '-', '_', '&', '()' and '/'

this is the expression

[\s\/\)\(\w&-]

I have tested this in various online testers and know it works, I just can't get it to work correctly in code. I get sysntax errors with anything I try.. any suggestions?

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

Answers:

Answer

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);
Answer

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 \()

Answer

Enclose your regex with delimiters:

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.