Skip to content

Commit

Permalink
Also escape -
Browse files Browse the repository at this point in the history
This enables you to escape a string that is inserted into a regex, for example, into a character class.

Fixes #9
  • Loading branch information
sindresorhus committed Apr 17, 2019
1 parent ea98098 commit e76291d
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 6 deletions.
8 changes: 5 additions & 3 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
/**
Escape RegExp special characters.
You can also use this to escape a string that is inserted into the middle of a regex, for example, into a character class.
@example
```
import escapeStringRegexp = require('escape-string-regexp');
const escapedString = escapeStringRegexp('how much $ for a 🦄?');
//=> 'how much \\$ for a 🦄\\?'
const escapedString = escapeStringRegexp('How much $ for a 🦄?');
//=> 'How much \\$ for a 🦄\\?'
new RegExp(escapedString);
```
*/
declare const escapeStringRegexp: (str: string) => string;
declare const escapeStringRegexp: (string: string) => string;

export = escapeStringRegexp;
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

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

module.exports = string => {
if (typeof string !== 'string') {
Expand Down
6 changes: 4 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ $ npm install escape-string-regexp
```js
const escapeStringRegexp = require('escape-string-regexp');

const escapedString = escapeStringRegexp('how much $ for a 🦄?');
//=> 'how much \\$ for a 🦄\\?'
const escapedString = escapeStringRegexp('How much $ for a 🦄?');
//=> 'How much \\$ for a 🦄\\?'

new RegExp(escapedString);
```

You can also use this to escape a string that is inserted into the middle of a regex, for example, into a character class.


## License

Expand Down
7 changes: 7 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,10 @@ test('main', t => {
'\\\\ \\^ \\$ \\* \\+ \\? \\. \\( \\) \\| \\{ \\} \\[ \\]'
);
});

test('escapes `-`', t => {
t.is(
escapeStringRegexp('foo - bar'),
'foo \\- bar'
);
});

0 comments on commit e76291d

Please sign in to comment.