jslib-escape-regex-str v0.9.0
escape-regex-str
Part of the @JSLib suite.
Escape special RegExp characters in a string.
Install
npm i @jslib/escape-regex-str
# or
yarn add @jslib/escape-regex-str
Targets:
- NodeJS v4.2 or later
- ES5 capatible browser
escapeRegexStr(str) ⇒ string
author: aMarCruz
Escapes special characters in a given string in preparation to be used as
argument of the JS RegExp
constructor, when you want to match the given
string as a literal substring.
Param | Type | Description |
---|---|---|
str | string | A raw string. |
Returns: string - Escaped string.
Example
import escapeRegexStr from '@jslib/escape-regex-str'
const template = 'Unicorn (white): $'
const regexStr = escapeRegexStr(template)
const regex = new RegExp(regexStr)
// without escapeRegexStr, the test fails.
expect('Unicorn (white): $1,000,000.00').to.match(regex)
Imports
JSLib functions works in strict mode and are compatible with:
- ES5 browsers, through the global object
_jslib
- ESM Bundlers, like WebPack and Rollup.
- ES modules of NodeJS v11.0 with the
--experimental-modules
flag. - CommonJS modules of NodeJS.
- Babel and TypeScript, through ES Module Interop.
The ES6 import of the examples is routed to "index.mjs" by the module
property of package.json, since "index.js" is the CommonJS version, routed by the "main" property to be used by NodeJS require()
.
Unlike the CommonJS and Browser variants, the ESM is a pure, unstranspilled ES6 version (neither NodeJS nor the blunders should have a problem with this).
TypeScript
TypeScript does not recognize the module
property and will use the CommonJS version so, if you are using ES6 imports, please enable esModuleInterop
in your tsconfig.json.
The export = require()
syntax must work with no issues.
6 years ago