Skip to content

Commit 732905d

Browse files
Escape - in a way that’s compatible with Unicode patterns (#21)
Co-authored-by: Sindre Sorhus <[email protected]>
1 parent 5085b25 commit 732905d

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

index.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
'use strict';
22

3-
const matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g;
4-
53
module.exports = string => {
64
if (typeof string !== 'string') {
75
throw new TypeError('Expected a string');
86
}
97

10-
return string.replace(matchOperatorsRegex, '\\$&');
8+
// Escape characters with special meaning either inside or outside character sets.
9+
// Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.
10+
return string
11+
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
12+
.replace(/-/g, '\\u002d');
1113
};

test.js

+8-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,13 @@ test('main', t => {
1111
test('escapes `-`', t => {
1212
t.is(
1313
escapeStringRegexp('foo - bar'),
14-
'foo \\- bar'
14+
'foo \\u002d bar'
15+
);
16+
});
17+
18+
test('escapes `-` in a way compatible with the Unicode flag', t => {
19+
t.regex(
20+
'-',
21+
new RegExp(escapeStringRegexp('-'), 'u')
1522
);
1623
});

0 commit comments

Comments
 (0)