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 thatstring
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
4 Answers
Reset to default 2You 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
版权声明:本文标题:javascript - How to take the string value out of its scope(unstring)? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744771905a2624389.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论