escapeRegExp.js 871 B

123456789101112131415161718192021222324252627282930313233
  1. var toString = require('./toString');
  2. /**
  3. * Used to match `RegExp`
  4. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  5. */
  6. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
  7. reHasRegExpChar = RegExp(reRegExpChar.source);
  8. /**
  9. * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
  10. * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
  11. *
  12. * @static
  13. * @memberOf _
  14. * @since 3.0.0
  15. * @category String
  16. * @param {string} [string=''] The string to escape.
  17. * @returns {string} Returns the escaped string.
  18. * @example
  19. *
  20. * _.escapeRegExp('[lodash](https://lodash.com/)');
  21. * // => '\[lodash\]\(https://lodash\.com/\)'
  22. */
  23. function escapeRegExp(string) {
  24. string = toString(string);
  25. return (string && reHasRegExpChar.test(string))
  26. ? string.replace(reRegExpChar, '\\$&')
  27. : string;
  28. }
  29. module.exports = escapeRegExp;