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