Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Regex, where to use escape characters?

Tags:

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&-]);
like image 469
Avien Avatar asked Apr 01 '11 13:04

Avien


People also ask

Which characters should be escaped in regex?

Operators: * , + , ? , | Anchors: ^ , $ Others: . , \ In order to use a literal ^ at the start or a literal $ at the end of a regex, the character must be escaped.

How do you escape a string in regex?

The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space.

Do I need to escape period in regex?

(dot) metacharacter, and can match any single character (letter, digit, whitespace, everything). You may notice that this actually overrides the matching of the period character, so in order to specifically match a period, you need to escape the dot by using a slash \. accordingly.


2 Answers

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);
like image 57
R. Martinho Fernandes Avatar answered Sep 20 '22 01:09

R. Martinho Fernandes


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

like image 45
3rgo Avatar answered Sep 18 '22 01:09

3rgo