Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape regular expression special characters using javascript? [duplicate]

People also ask

How do you skip special characters in regex?

for metacharacters such as \d (digit), \D (non-digit), \s (space), \S (non-space), \w (word), \W (non-word). to escape special regex characters, e.g., \. for . , \+ for + , \* for * , \? for ? . You also need to write \\ for \ in regex to avoid ambiguity.

How do you escape a Metacharacter in regex?

To match any of the metacharacters literally, one needs to escape these characters using a backslash ( \ ) to suppress their special meaning. Similarly, ^ and $ are anchors that are also considered regex metacharacters.

What does \\ mean in regex?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \.


Use the \ character to escape a character that has special meaning inside a regular expression.

To automate it, you could use this:

function escapeRegExp(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape

Update: The abovementioned proposal was rejected, so keep implementing this yourself if you need it.


Use the backslash to escape a character. For example:

/\\d/

This will match \d instead of a numeric character


With \ you escape special characters

Escapes special characters to literal and literal characters to special.

E.g: /\(s\)/ matches '(s)' while /(\s)/ matches any whitespace and captures the match.

Source: http://www.javascriptkit.com/javatutors/redev2.shtml