escapeRegExpChar.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. /** Used to escape characters for inclusion in compiled regexes. */
  2. var regexpEscapes = {
  3. '0': 'x30', '1': 'x31', '2': 'x32', '3': 'x33', '4': 'x34',
  4. '5': 'x35', '6': 'x36', '7': 'x37', '8': 'x38', '9': 'x39',
  5. 'A': 'x41', 'B': 'x42', 'C': 'x43', 'D': 'x44', 'E': 'x45', 'F': 'x46',
  6. 'a': 'x61', 'b': 'x62', 'c': 'x63', 'd': 'x64', 'e': 'x65', 'f': 'x66',
  7. 'n': 'x6e', 'r': 'x72', 't': 'x74', 'u': 'x75', 'v': 'x76', 'x': 'x78'
  8. };
  9. /** Used to escape characters for inclusion in compiled string literals. */
  10. var stringEscapes = {
  11. '\\': '\\',
  12. "'": "'",
  13. '\n': 'n',
  14. '\r': 'r',
  15. '\u2028': 'u2028',
  16. '\u2029': 'u2029'
  17. };
  18. /**
  19. * Used by `_.escapeRegExp` to escape characters for inclusion in compiled regexes.
  20. *
  21. * @private
  22. * @param {string} chr The matched character to escape.
  23. * @param {string} leadingChar The capture group for a leading character.
  24. * @param {string} whitespaceChar The capture group for a whitespace character.
  25. * @returns {string} Returns the escaped character.
  26. */
  27. function escapeRegExpChar(chr, leadingChar, whitespaceChar) {
  28. if (leadingChar) {
  29. chr = regexpEscapes[chr];
  30. } else if (whitespaceChar) {
  31. chr = stringEscapes[chr];
  32. }
  33. return '\\' + chr;
  34. }
  35. module.exports = escapeRegExpChar;