Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
11
rated 0 times [  16] [ 5]  / answers: 1 / hits: 39850  / 8 Years ago, thu, august 25, 2016, 12:00:00

So I have a RegExp regex = /asd/



I am storing it as a as a key in my key-val store system.



So I say str = String(regex) which returns /asd/.



Now I need to convert that string back to a RegExp.



So I try: RegExp(str) and I see //asd//



this is not what I want. It is not the same as /asd/



Should I just remove the first and last characters from the string before converting it to regex? That would get me the desired result in this situation, but wouldn't necessarily work if the RegExp had modifiers like /i or /g



Is there a better way to do this?


More From » regex

 Answers
1
const regex = /asd/gi;

converting RegExp to String


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

then back to RegExp


const obj2 = JSON.parse(string);
const regex2 = new RegExp(obj2.source, obj2.flags);

Requires ES6+.


[#60913] Tuesday, August 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pierce

Total Points: 315
Total Questions: 103
Total Answers: 89

Location: Svalbard and Jan Mayen
Member since Mon, Jun 7, 2021
3 Years ago
;