UNPKG

871 BJavaScriptView Raw
1var toString = require('./toString');
2
3/**
4 * Used to match `RegExp`
5 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
6 */
7var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
8 reHasRegExpChar = RegExp(reRegExpChar.source);
9
10/**
11 * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
12 * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
13 *
14 * @static
15 * @memberOf _
16 * @since 3.0.0
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 = toString(string);
27 return (string && reHasRegExpChar.test(string))
28 ? string.replace(reRegExpChar, '\\$&')
29 : string;
30}
31
32module.exports = escapeRegExp;