0.9.0 • Published 6 years ago

jslib-escape-regex-str v0.9.0

Weekly downloads
1
License
MIT
Repository
github
Last release
6 years ago

escape-regex-str

npm Version License

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.

ParamTypeDescription
strstringA 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:

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.