Skip to content

Commit

Permalink
XRegExp.escape: Escape # and , in way that works with ES6 flag u (#323)
Browse files Browse the repository at this point in the history
  • Loading branch information
slevithan committed Feb 16, 2021
1 parent 93f3001 commit c34a926
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 9 deletions.
14 changes: 6 additions & 8 deletions src/xregexp.js
Original file line number Diff line number Diff line change
Expand Up @@ -796,18 +796,16 @@ XRegExp.cache.flush = (cacheName) => {
// - `[()*+?.$|` - context: default
// - `]` - context: default with flag u or if forming the end of a character class
// - `{}` - context: default with flag u or if part of a valid/complete quantifier pattern
// - `,` - context: default if in a position that causes an unescaped `{` to turn into a
// quantifier. E.g. /^a{1\,2}$/ matches 'a{1,2}', but /^a{1,2}$/ matches 'a' or 'aa'.
// - `#` and whitespace - context: default with flag x
// - `,` - context: default if in a position that causes an unescaped `{` to turn into a quantifier.
// Ex: `/^a{1\,2}$/` matches `'a{1,2}'`, but `/^a{1,2}$/` matches `'a'` or `'aa'`
// - `#` and <whitespace> - context: default with flag x
// - `^` - context: default, and context: class if it's the first character in the class
// - `-` - context: class if part of a valid character class range
XRegExp.escape = (str) => String(nullThrows(str)).
// Escape most special chars with a backslash
replace(/[\\\[\]{}()*+?.,^$|#]/g, '\\$&').
// Convert whitespace to \uNNNN since it can't be escaped when used with ES6 flag `u`
replace(/\s/g, (match) => `\\u${pad4(hex(match.charCodeAt(0)))}`).
// Convert hyphen to \x2D since it can't be escaped when used with ES6 flag `u`
replace(/-/g, '\\x2D');
replace(/[\\\[\]{}()*+?.^$|]/g, '\\$&').
// Convert to \uNNNN for special chars that can't be escaped when used with ES6 flag `u`
replace(/[\s#\-,]/g, (match) => `\\u${pad4(hex(match.charCodeAt(0)))}`);

/**
* Executes a regex search in a specified string. Returns a match array or `null`. If the provided
Expand Down
2 changes: 1 addition & 1 deletion tests/spec/s-xregexp-methods.js
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ describe('XRegExp.escape()', function() {
});

it('should handle escaping with ES6 flag u', function() {
expect(new RegExp('^' + XRegExp.escape(' - ') + '$', hasNativeU ? 'u' : '').test(' - ')).toBe(true);
expect(new RegExp('^' + XRegExp.escape(' \n-,#') + '$', hasNativeU ? 'u' : '').test(' \n-,#')).toBe(true);
});

it('should not escape nonmetacharacters', function() {
Expand Down

0 comments on commit c34a926

Please sign in to comment.