Skip to content

Escape - in a way that’s compatible with Unicode patterns #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
'use strict';

const matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g;

module.exports = string => {
if (typeof string !== 'string') {
throw new TypeError('Expected a string');
}

return string.replace(matchOperatorsRegex, '\\$&');
// Escape characters with special meaning either inside or outside character sets.
// 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.
return string
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
.replace(/-/g, '\\u002d');
};
9 changes: 8 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ test('main', t => {
test('escapes `-`', t => {
t.is(
escapeStringRegexp('foo - bar'),
'foo \\- bar'
'foo \\u002d bar'
);
});

test('escapes `-` in a way compatible with the Unicode flag', t => {
t.regex(
'-',
new RegExp(escapeStringRegexp('-'), 'u')
);
});