I have a good grasp on parsing a valid JSON string using JSON.parse('{"key" : "value"}')
.
But what happens when dealing with a valid JS object, but invalid JSON, such as: JSON.parse("{ key : 'value'}")
? The outcome of this example is an error:
Uncaught SyntaxError: Unexpected token k in JSON at position 2
My current focus is on a more intricate task. I aim to parse a string representing a JS object containing RegEx (not supported by JSON, but accepted in JS) into a JS object :
'{ key1 : /val1/g , key2 : /val2/i }'
The ultimate goal is to utilize this object with Mongoose and search for documents using it :
Model.find({
key1 : /val1/g ,
key2 : /val2/i
})
I have made attempts to apply a rather complex RegEx to the String, replacing /val1/g
with new RegEx("val1","i")
:
str = str.replace( /\/(.+?)\/(g?i?).+?(?=,|})/g , "new RegExp(`$1`,`$2`)" )
The .replace()
function successfully manipulates the string as intended. This results in:
{ key1 : new RegExp("val1","g") , key2 : new RegExp("val2","i") }
However, attempting to use JSON.parse
on it still fails because new RegEx("val1","i")
is not a valid value.