diff --git a/lodash.src.js b/lodash.src.js index e7d242ef7..69b0acd02 100644 --- a/lodash.src.js +++ b/lodash.src.js @@ -94,11 +94,10 @@ rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; /** - * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). - * In addition to special characters the forward slash is escaped to allow for - * easier `eval` use and `Function` compilation. + * Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns) + * and those outlined by [`EscapeRegExpPattern`](http://ecma-international.org/ecma-262/6.0/#sec-escaperegexppattern). */ - var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, + var reRegExpChars = /[\/^$\\.*+?()[\]{}|\n\r\u2028\u2029]/g, reHasRegExpChars = RegExp(reRegExpChars.source); /** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */ @@ -10491,7 +10490,7 @@ function escapeRegExp(string) { string = baseToString(string); return (string && reHasRegExpChars.test(string)) - ? string.replace(reRegExpChars, '\\$&') + ? string.replace(reRegExpChars, function(chr) { return '\\' + (stringEscapes[chr] || chr); }) : (string || '(?:)'); } diff --git a/test/test.js b/test/test.js index 76b7ef417..76b02c574 100644 --- a/test/test.js +++ b/test/test.js @@ -4222,29 +4222,31 @@ QUnit.module('lodash.escapeRegExp'); (function() { + var escaped = '\\/\\^\\$\\.\\*\\+\\?\\(\\)\\[\\]\\{\\}\\|\\n\\r\\u2028\\u2029\\\\', + unescaped = '/^$.*+?()[]{}|\n\r\u2028\u2029\\'; + test('should escape values', 1, function() { - var escaped = '\\.\\*\\+\\?\\^\\$\\{\\}\\(\\)\\|\\[\\]\\/\\\\', - unescaped = '.*+?^${}()|[\]\/\\'; - - escaped += escaped; - unescaped += unescaped; - - strictEqual(_.escapeRegExp(unescaped), escaped); + strictEqual(_.escapeRegExp(unescaped + unescaped), escaped + escaped); }); test('should handle strings with nothing to escape', 1, function() { strictEqual(_.escapeRegExp('abc'), 'abc'); }); + test('should return `"(?:)"` when provided nullish or empty string values', 3, function() { + strictEqual(_.escapeRegExp(null), '(?:)'); + strictEqual(_.escapeRegExp(undefined), '(?:)'); + strictEqual(_.escapeRegExp(''), '(?:)'); + }); + test('should work with `eval` and `Function`', 2, function() { - var string = '[lodash](https://lodash.com/)', - escaped = _.escapeRegExp(string), - regexp = eval('(/' + escaped + '/)'); + var actual = _.escapeRegExp(unescaped), + regexp = eval('(/' + actual + '/)'); - ok(regexp.test(string)); + ok(regexp.test(unescaped)); - regexp = Function('return /' + escaped + '/')(); - ok(regexp.test(string)); + regexp = Function('return /' + actual + '/')(); + ok(regexp.test(unescaped)); }); }()); @@ -17819,7 +17821,6 @@ 'camelCase', 'capitalize', 'escape', - 'escapeRegExp', 'kebabCase', 'pad', 'padLeft',