JavaScript Store and Load Regex as String

November 3, 2021

Rgex To String

const regex = /(?<year>\d{4})-(?<month>\d{1,2})-(?<day>\d{1,2})/

const obj = {flags: regex.flags, source: regex.source};
const string = JSON.stringify(obj);

Regex From String

const obj = JSON.parse(string);
const regex = new RegExp(obj.source, obj.flags);
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.