1var baseToString = require('../internal/baseToString'); 2 3/** 4 * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). 5 * In addition to special characters the forward slash is escaped to allow for 6 * easier `eval` use and `Function` compilation. 7 */ 8var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, 9 reHasRegExpChars = RegExp(reRegExpChars.source); 10 11/** 12 * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", 13 * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. 14 * 15 * @static 16 * @memberOf _ 17 * @category String 18 * @param {string} [string=''] The string to escape. 19 * @returns {string} Returns the escaped string. 20 * @example 21 * 22 * _.escapeRegExp('[lodash](https://lodash.com/)'); 23 * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' 24 */ 25function escapeRegExp(string) { 26 string = baseToString(string); 27 return (string && reHasRegExpChars.test(string)) 28 ? string.replace(reRegExpChars, '\\$&') 29 : string; 30} 31 32module.exports = escapeRegExp; 33 34