I have a string which consist of a number with operators. Like : displayText ="123+12*23".And I want to convert it into number so that all the mathematical operations will be performed. Any idea how can I do that
Asked
Active
Viewed 74 times
0
-
4You're looking for the [**`eval()`**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) function. – Obsidian Age Jan 19 '18 at 03:47
-
1You need to define all your operators and their precedence first as this determines the complexity of the possible solutions. – le_m Jan 19 '18 at 03:47
-
1Read about [`eval`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval). But be careful when using it (check if the string contains any harmful code before evaluating). – ibrahim mahrir Jan 19 '18 at 03:47
-
`eval()` is not necessary – guest271314 Jan 19 '18 at 03:59
-
See also [Chrome App: Doing maths from a string](https://stackoverflow.com/q/32982719/) – guest271314 Jan 19 '18 at 04:07
2 Answers
0
What you are looking for here is the Javascript's native eval() function.
const displayText = "123+12*23";
const result = eval(displayText);
The above code will produce the result of the expression i.e. 399.

Nabin Paudyal
- 1,591
- 8
- 14
-
1Three minutes ago same answer was given in comment section also no variation from the other answer – brk Jan 19 '18 at 03:51
0
You can use Function
let displayText = "123+12*23";
let num = str => new Function(`return ${str}`)();
console.log(num(displayText));

guest271314
- 1
- 15
- 104
- 177
-
-
-
@Pablo: Not quite. It doesn't have access to the local scope the function is created in (it only has access to global scope). – Felix Kling Jan 19 '18 at 04:19