admin管理员组

文章数量:1391721

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?

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?

Share Improve this question asked Aug 19, 2015 at 14:18 RegarBoyRegarBoy 3,5211 gold badge25 silver badges47 bronze badges 7
  • It sounds like you are looking for eval, but you really shouldn't use that. Where do you get that string from? – Bergi Commented Aug 19, 2015 at 14:20
  • eval()? – Delgan Commented Aug 19, 2015 at 14:20
  • I have no idea what you mean by "string scope". – Bergi Commented Aug 19, 2015 at 14:21
  • from another js file but I the value of option element which returns string – RegarBoy Commented Aug 19, 2015 at 14:22
  • 1 @developer You really should link the option to a function that you can call, not to a string. – Bergi Commented Aug 19, 2015 at 14:23
 |  Show 2 more ments

4 Answers 4

Reset to default 2

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

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);

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)

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

本文标签: javascriptHow to take the string value out of its scope(unstring)Stack Overflow