Aller au contenu principal

escapeRegExp()

escapeRegExp(str): string

Escapes RegExp special characters in a string.

ESCAPES

^, $, \, ., *, +, ?, (, ), [, ], {, }, |.


Parameters

str: string

The string to escape.


Returns: string

The escaped string safe for use in RegExp.


Since

2.0.0


Performance

O(n) time where n is string length. Single regex pass.


Also known as

escapeRegExp (Lodash, es-toolkit) · ❌ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)


Example

escapeRegExp('[lodash](https://lodash.com/)');
// => '\\[lodash\\]\\(https://lodash\\.com/\\)'

escapeRegExp('$100.00');
// => '\\$100\\.00'

// Use to create safe regex patterns
const userInput = 'hello.*world';
const pattern = new RegExp(escapeRegExp(userInput));
pattern.test('hello.*world'); // => true
pattern.test('helloXworld'); // => false