tiny-escape
v1.1.0
Published
Escape special characters for use in regular expressions. Like escape-string-regexp, ships ESM + CJS.
Downloads
71
Maintainers
Readme
tiny-escape
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); // true201 bytes gzipped. Zero dependencies.

Install
npm install tiny-escapeUsage
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); // trueDifferences 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.
