All files / regexp/src escapeString.ts

100% Statements 3/3
100% Branches 0/0
100% Functions 2/2
100% Lines 2/2

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21                              1x     1x    
/**
 * Escapes a string for use within RegExp
 *
 * @see https://github.com/sindresorhus/escape-string-regexp
 *
 * @example
 * Escape special characters
 * ```ts
 * const r = new RegExp(escapeString("(a-b)[.]"));
 * const result = r.test("(a-b)[.]");
 * console.log(result); // true
 * ```
 *
 * @returns the escaped string
 */
export const escapeString = (str: string): string => {
  // Escape characters with special meaning either inside or outside character sets.
  // Use a simple backslash escape when it’s always valid, and a `\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.
  return str.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
};