Languages
[Edit]
EN

TypeScript - escape special characters in regular expression pattern

3 points
Created by:
Welsh
902

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 TypeScript.

Practical example:

Output:

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 \\.

Output:

 

2. Escape in syntax pattern

Edit

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

Output:

 

Optimal solutions

Edit

1. Best performance

Edit

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

Output:

 

2. Quite good performance:

Edit

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

Output:

 

See also

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

Alternative titles

  1. TypeScript - escape special characters in regular expression
  2. TypeScript - escape RegExp special characters
  3. TypeScript - 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