@randajan/regex-parser
v0.0.2
Published
Convert between JavaScript RegExp and its string representation. Simple, safe and lightweight.
Maintainers
Readme
@randajan/regex-parser
Convert between JavaScript RegExp objects and their /pattern/flags string form — simple, safe and lightweight.
Install
npm i @randajan/regex-parserQuick use
import { rgxToStr, strToRgx } from "@randajan/regex-parser";
// or: const { rgxToStr, strToRgx } = require("@randajan/regex-parser");
const re = /hello\/world/i;
const str = rgxToStr(re); // "/hello\\/world/i"
const re2 = strToRgx(str); // ⇢ /hello\/world/iAPI
rgxToStr(regexp) → string
Serialises a RegExp into /pattern/flags, escaping only those / that are not already escaped.
strToRgx(string, strict = false) → RegExp
- If the string matches
/pattern/flags, parse it. - Else
- when strict = false (default) return a safe literal regex with the text escaped,
- when strict = true throw
SyntaxError.
strToRgx("/\d+/g"); // → /\d+/g
strToRgx("user.name?"); // → /user\.name\?/
strToRgx("user.name?", true); // throwsExample round‑trip test
const originals = [/foo\/bar/i, /a+b*c?.(x|y)/g];
originals.forEach(r => {
const r2 = strToRgx(rgxToStr(r));
console.assert(r2.source === r.source && r2.flags === r.flags);
});Why another regex helper?
- Zero dependencies – <1 kB min+gzip
- Predictable – strict mode prevents silent surprises
- Universal – Node ≥12 & all modern browsers
License
MIT © randajan
