From e76291d337900dbfba3b2e04d71c6d718ec7199b Mon Sep 17 00:00:00 2001 From: Sindre Sorhus Date: Wed, 17 Apr 2019 14:46:19 +0700 Subject: [PATCH] Also escape `-` This enables you to escape a string that is inserted into a regex, for example, into a character class. Fixes #9 --- index.d.ts | 8 +++++--- index.js | 2 +- readme.md | 6 ++++-- test.js | 7 +++++++ 4 files changed, 17 insertions(+), 6 deletions(-) diff --git a/index.d.ts b/index.d.ts index a8ecae3..7d34edc 100644 --- a/index.d.ts +++ b/index.d.ts @@ -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; diff --git a/index.js b/index.js index 08fc586..58217a4 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,6 @@ 'use strict'; -const matchOperatorsRegex = /[|\\{}()[\]^$+*?.]/g; +const matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g; module.exports = string => { if (typeof string !== 'string') { diff --git a/readme.md b/readme.md index 375585f..157472b 100644 --- a/readme.md +++ b/readme.md @@ -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 diff --git a/test.js b/test.js index 2a22573..7fac094 100644 --- a/test.js +++ b/test.js @@ -7,3 +7,10 @@ test('main', t => { '\\\\ \\^ \\$ \\* \\+ \\? \\. \\( \\) \\| \\{ \\} \\[ \\]' ); }); + +test('escapes `-`', t => { + t.is( + escapeStringRegexp('foo - bar'), + 'foo \\- bar' + ); +});