Home Manual Reference Source Test

src/lib/regexp.ts

  1. /** Special characters in regular expressions. */
  2. export const specialChars = ['[', '\\', '^', '$', '.', '|', '?', '*', '+', '(', ')', ']'];
  3.  
  4. /** A regular expression that matches all special characters in regular expressions. */
  5. export const specialCharsRegExp = new RegExp(
  6. `(${specialChars.map((c) => `\\${c}`).join('|')})`,
  7. 'g'
  8. );
  9.  
  10. /**
  11. * Returns a string with all special regular expression characters escaped.
  12. * @param source The string to escape.
  13. */
  14. export function escapeForRegExp(source: string) {
  15. return source.replace(specialCharsRegExp, '\\$1');
  16. }