Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Modern escape-string-regexp replacement — escape regex special chars. TypeScript, ESM + CJS, zero deps.

License

Notifications You must be signed in to change notification settings

ofershap/tiny-escape

Repository files navigation

tiny-escape

npm version npm downloads CI TypeScript License: MIT

Escape special characters in a string for use in a regular expression. Same behavior as escape-string-regexp, but ships both ESM and CJS.

import { escapeRegExp } from "tiny-escape";

const input = "price is $5.00 (USD)";
new RegExp(escapeRegExp(input)).test(input); // true

201 bytes gzipped. Zero dependencies.

Demo

Demo built with remotion-readme-kit

Install

npm install tiny-escape

Usage

import { escapeRegExp } from "tiny-escape";

escapeRegExp("hello.world"); // "hello\\.world"
escapeRegExp("[test] (1+1)"); // "\\[test\\] \\(1\\+1\\)"
escapeRegExp("foo|bar"); // "foo\\|bar"
escapeRegExp("a-b"); // "a\\x2db"

const userInput = "How much $ for mass?";
const re = new RegExp(escapeRegExp(userInput), "i");
re.test(userInput); // true

Differences from escape-string-regexp

escape-string-regexp v5 is ESM-only. If you require("escape-string-regexp") you get ERR_REQUIRE_ESM. tiny-escape works with both import and require().

escape-string-regexp tiny-escape
CJS support v4 only (v5 ESM-only) ESM + CJS
TypeScript native (v5) native
Export default named

Migrating from escape-string-regexp

- import escapeStringRegexp from "escape-string-regexp";
- const escaped = escapeStringRegexp(input);
+ import { escapeRegExp } from "tiny-escape";
+ const escaped = escapeRegExp(input);

API

escapeRegExp(string: string): string

Escapes | \ { } ( ) [ ] ^ $ + * ? . and -.

Throws TypeError if the input is not a string.

Author

Made by ofershap

LinkedIn GitHub

License

MIT © Ofer Shapira

About

Modern escape-string-regexp replacement — escape regex special chars. TypeScript, ESM + CJS, zero deps.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

 

Packages

 
 
 

Contributors