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

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

Posted by: admin November 30, 2017 Leave a comment

Questions:

This question already has an answer here:

Answers:

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.

Questions:
Answers:

Use the backslash to escape a character. For example:

/\d/

This will match \d instead of a numeric character

Questions:
Answers:

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