2025-09-05 14:59:21 +08:00

21 lines
631 B
JavaScript

export function jsonStringify(value) {
return JSON.stringify(value, regExpReplacer);
}
export function jsonParse(value) {
return JSON.parse(value, regExpReviver);
}
function regExpReplacer(_key, value) {
if (value instanceof RegExp) {
return `--REGEX ${value.toString()}`;
}
return value;
}
function regExpReviver(_key, value) {
const withOperator = typeof value === "string" && value.match(/^--([A-Z]+) (.+)$/) || [];
if (withOperator[1] === "REGEX") {
const regex = withOperator[2]?.match(/\/(.*)\/([dgimsuy]*)$/);
return regex?.[1] ? new RegExp(regex[1], regex[2] || "") : value;
}
return value;
}