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.
Demo built with remotion-readme-kit
npm install tiny-escapeimport { 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); // trueescape-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 |
- import escapeStringRegexp from "escape-string-regexp";
- const escaped = escapeStringRegexp(input);
+ import { escapeRegExp } from "tiny-escape";
+ const escaped = escapeRegExp(input);Escapes | \ { } ( ) [ ] ^ $ + * ? . and -.
Throws TypeError if the input is not a string.
