escapeRegExp.js 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. var baseToString = require('../internal/baseToString'),
  2. escapeRegExpChar = require('../internal/escapeRegExpChar');
  3. /**
  4. * Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns)
  5. * and those outlined by [`EscapeRegExpPattern`](http://ecma-international.org/ecma-262/6.0/#sec-escaperegexppattern).
  6. */
  7. var reRegExpChars = /^[:!,]|[\\^$.*+?()[\]{}|\/]|(^[0-9a-fA-Fnrtuvx])|([\n\r\u2028\u2029])/g,
  8. reHasRegExpChars = RegExp(reRegExpChars.source);
  9. /**
  10. * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?",
  11. * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`.
  12. *
  13. * @static
  14. * @memberOf _
  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 = baseToString(string);
  25. return (string && reHasRegExpChars.test(string))
  26. ? string.replace(reRegExpChars, escapeRegExpChar)
  27. : (string || '(?:)');
  28. }
  29. module.exports = escapeRegExp;