Languages
[Edit]
EN

JavaScript - escape special characters in regular expression pattern

13 points
Created by:
Mikolaj
519

In this short article, we would like to show how to escape special characters from patterns that we want to use with regular expressions in JavaScript.

Practical example:

Hint: the above approach is useful when we want to escape all special characters automatically.

 

Manual escape

Edit

We can escape special characters manually by using \ or \\ before them in patterns.

1. Escape in string pattern

Edit

In strings, we should escape special characters using \\.

 

2. Escape in syntax pattern

Edit

In syntax patterns, we should escape special characters using \.

 

Optimal solutions

Edit

Regular expressions are slower than source code, so using some tricks we are able to get optimal performance on pattern escape.

1. Best performance

Edit

escapePattern() function is faster by about 2.5x than the replace-based version.

 

1. Quite good performance:

Edit

escapePattern() function is faster by about 1.5x than the replace-based version.

 

See also

Edit
  1. TypeScript - escape special characters in regular expression pattern

Alternative titles

  1. JavaScript - escape special characters in regular expression
  2. JavaScript - escape RegExp special characters
  3. JavaScript - escape regex special characters
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join