I know how to parse a valid JSON string : JSON.parse('{"key" : "value"}').
But what about a valid JS object, but invalid JSON, like : JSON.parse("{ key : 'value'}") ?
The example above throws :
Uncaught SyntaxError: Unexpected token k in JSON at position 2
My actual goal is even trickier. I want to parse a string of a JS object containing RegEx (unsupported by JSON but supported by JS) into a JS object :
'{ key1 : /val1/g , key2 : /val2/i }'
I eventually want to use this object with Mongoose and find documents with it :
Model.find({
key1 : /val1/g ,
key2 : /val2/i
})
I have tried applying a fairly complex RegEx to my String, replacing /val1/g with new RegEx("val1","i") :
str = str.replace( /\/(.+?)\/(g?i?).+?(?=,|})/g , "new RegExp(`$1`,`$2`)" )
The .replace() operation works and modifies the string the way I want it. It yields :
{ key1 : new RegExp("val1","g") , key2 : new RegExp("val2","i") }
But when I try to apply JSON.parse to it, it still fails because new RegEx("val1","i")is not a valid value.
evalis what you're looking for?