Skip to content

escapeRegExp

Escapes regular expression metacharacters (. * + ? ^ $ { } ( ) | [ ] \) in a string so it can be safely embedded in a RegExp pattern.

Use this before building a RegExp from untrusted or dynamic input — without it, characters like . or ( change the pattern’s meaning instead of being matched literally.

Available since v3.0.0

import { escapeRegExp } from '@helpers4/string';
// or, from the all-in-one package (same code, one install):
import { escapeRegExp } from 'helpers4/string';
escapeRegExp(str: string): string
ParameterTypeDescription
strstringThe string to escape

string — The escaped string, safe to embed in a RegExp pattern

Escape metacharacters before building a RegExp

Section titled “Escape metacharacters before building a RegExp”

Without escaping, ”.” and ”?” would change the pattern’s meaning.

escapeRegExp('1 + 1 = 2?')
// => '1 \\+ 1 = 2\\?'

Escaping lets user-provided text be matched literally instead of as a pattern.

const userInput = 'a.b';
new RegExp(escapeRegExp(userInput)).test('a.b')   // => true
new RegExp(escapeRegExp(userInput)).test('axb')   // => false (literal '.', not "any char")

View source on GitHub