Javascript. Changing a string to an operator

Asked

Viewed 59 times

-2

Hello, I wonder if there’s any way I can get the value + in the middle if a string and leave him as a operator ?

Example:

Of:

var string = "15 + 20 + 30"

To:

var convert = "15" + "20" + "30"

Obs: the amount of values inside is undefined can be "15 + 15" or even "1 + 1 + 1 + 1 + 1 + 1 + 1"

  • You can do something really simple like '1 + 1 + 1 + 1 + 1 + 1 + 1'.split('+').reduce((a,b) => parseInt(a) + parseInt(b), 0)

2 answers

1

You can split by the operator, the resutlado will be a string array with the values:

var string = '15 + 15 + 15';
var convert = string.split('+');

// convert > ["15", "15", "15"]

// para somar: 
var sum = 0;
convert.forEach( num => {
  sum += parseInt(num);
})

0


You can use the function eval() that computes a string crossing as expression:

console.log(eval("1 + 1 + 1 + 1 + 1 + 1 + 1"));

// pode inclusive usar expressões mais complexas:
var x = "10";
console.log(eval("x/(2+3)"));

  • who negative can explain what this response has bad if it answers exactly what was asked, with example and also link to the original documentation???

  • 2

    Only those who voted negative can answer this accurately, but most likely it’s because your answer doesn’t explain much about Eval, and the link you shared has a topic Never use eval()!. Theoretically your reference says never to use your answer

  • may be, but it’s like saying "look has a format command here, but never use it" :) I read this and found the way it’s written exaggerated, if it was to never use it should be removed :) but Welcome the comment Rafael. A simple if can be as disastrous as if misused

  • Thanks for the =D tip I used Eval() on my calculator. it helped a lot

Browser other questions tagged

You are not signed in. Login or sign up in order to post.