UNPKG

@randajan/regex-parser

Version:

Convert between JavaScript RegExp and its string representation. Simple, safe and lightweight.

22 lines (21 loc) 708 B
// src/index.js var _regex = /^\/((?:\\.|[^\\/])+)\/([a-z]*)$/i; var _regexEsc = /[.*+?^${}()|[\]\\]/g; var _unsafeSlash = /(^|[^\\])\//g; var rgxToStr = (rgx) => { if (!(rgx instanceof RegExp)) throw new TypeError("Expected RegExp"); const pattern = rgx.source.replace(_unsafeSlash, "$1\\/"); return `/${pattern}/${rgx.flags}`; }; var strToRgx = (str, strict = false) => { if (typeof str !== "string") throw new TypeError("Expected string"); const m = str.match(_regex); if (m) return new RegExp(m[1], m[2]); if (strict) throw new SyntaxError("Invalid regex string"); return new RegExp(str.replace(_regexEsc, "\\$&")); }; export { rgxToStr, strToRgx }; //# sourceMappingURL=index.js.map