0

I have looked through string methods, but couldn't find any method to throw the string value out of its scope. Is there any function to unString the string in JavaScript? For instance if I receive a calculation in a string form from another file:

var five = 5
var three = 3
var calculation = five * three;
var string = 'calculation * 1232123 - five + three';

How can I store that received string in a variable where those values get out of string scope and get calculated? Is there a way or is there a method to do so?

RegarBoy
  • 3,228
  • 1
  • 23
  • 44

4 Answers4

2

You can use eval function. But remember, that eval is evil.

Jacobian
  • 10,122
  • 29
  • 128
  • 221
1

Maybe eval() is what you are looking for? Eval "parses" the string and runs whatever text is there (or evaluates i guess)

var five = 5
eval("five + five")

This outputs 10 if you run it. Take note! This will solve the specific question you ask, but its probably not a good way to solve your actual problem (that we dont know much about)

BobbyTables
  • 4,481
  • 1
  • 31
  • 39
  • 1
    Yup. Provided the string is from a *trusted source*, using `eval` is perfectly fine and the most direct way to address the OP's question given the level of detail we have. From an *untrusted source*, they'd have to write an expression parser. – T.J. Crowder Aug 19 '15 at 14:46
1

You can use a template string and JSON.parse

var five = 5;
var three = 3;
var calculation = five * three;
var string = `${calculation * 1232123 - five + three}`;
JSON.parse(string);
Ari
  • 1,595
  • 12
  • 20
0

If you have a sentence like this:

let str= "Hello World"

and you want to unstring the value or remove quotes from it, you can do something like this:

str = str.replace(/"/g,"")

Now value of str is Hello World

  • If you want more details, visit this StackOverflow post: https://stackoverflow.com/questions/19156148/i-want-to-remove-double-quotes-from-a-string/34245366 –  Feb 23 '20 at 13:59