Search code examples
javascriptecmascript-5

JavaScript - Parse single variable in string


Whats be best way to parse a single variable in a string without using eval?

I have strings as following:

"'myString'" -> should be a string with value "myString"
"true"       -> should be a boolean with value true
"12"         -> should be a number with value 12

This is working but I would like a more secure solution:

var parsedValue = eval(stringToParse); 

Solution

  • JSON.parse should do it, but you have to replace single quotes with doubles

    JSON.parse("'myString'".replace(/'/g,'"'))
    JSON.parse("true")
    JSON.parse("12")