Skip to content

escapeRegExp function ​

Escapes a text so that it matches literally in a regular expression, v flag included.

ts
import { escapeRegExp } from 'utils';

Signature ​

ts
export function escapeRegExp(input: string): string

Parameters ​

NameDescription
inputThe literal text to search for.

Returns ​

The text with every regular expression syntax character escaped.

Example ​

ts
new RegExp(`^${escapeRegExp('1+1=2?')}$`, 'v').test('1+1=2?'); // true

Tests ​

Line coverage: 100 %.

  • ✅ matches "1+1=2?" literally with the v flag
  • ✅ matches "(a|b)[c]{d}" literally with the v flag
  • ✅ matches "C:\path\file.txt" literally with the v flag
  • ✅ matches "price: $5.00 ^_^" literally with the v flag
  • ✅ matches "a-b & c" literally with the v flag
  • ✅ matches "plain" literally with the v flag
  • ✅ matches literally with the u flag and without flags
  • ✅ escapes the syntax characters only

Source ​

src/string/escape-reg-exp.ts (on GitHub)

Source code
ts
const SYNTAX_CHARACTERS: ReadonlySet<string> = new Set([
  '\\',
  '^',
  '$',
  '.',
  '*',
  '+',
  '?',
  '(',
  ')',
  '[',
  ']',
  '{',
  '}',
  '|',
  '/',
]);

/**
 * Escapes a text so that it matches literally in a regular expression, `v` flag included.
 *
 * @param input - The literal text to search for.
 * @returns The text with every regular expression syntax character escaped.
 * @example
 * new RegExp(`^${escapeRegExp('1+1=2?')}$`, 'v').test('1+1=2?'); // true
 */
export function escapeRegExp(input: string): string {
  return Array.from(input, (character) => (SYNTAX_CHARACTERS.has(character) ? `\\${character}` : character)).join('');
}
Test file
ts
import { escapeRegExp } from './escape-reg-exp';

describe(escapeRegExp, () => {
  it.for(['1+1=2?', '(a|b)[c]{d}', String.raw`C:\path\file.txt`, 'price: $5.00 ^_^', 'a-b & c', 'plain'])(
    'matches %j literally with the v flag',
    (input) => {
      const pattern = new RegExp(`^${escapeRegExp(input)}$`, 'v');
      expect(pattern.test(input)).toBe(true);
    },
  );

  it('matches literally with the u flag and without flags', () => {
    const input = '(a|b)*.c';
    const unicodePattern = new RegExp(escapeRegExp(input), 'u');
    const plainPattern = new RegExp(escapeRegExp(input));
    expect(unicodePattern.test(`x${input}x`)).toBe(true);
    expect(plainPattern.test('ab.c')).toBe(false);
  });

  it('escapes the syntax characters only', () => {
    expect(escapeRegExp('a.b')).toBe(String.raw`a\.b`);
    expect(escapeRegExp('abc')).toBe('abc');
  });
});

Keywords: escape, reg, exp, strings, function

Generated from the JSDoc of the sources.