0

Right now I have a variable which is storing a string.

var value = "66+88";

How can I replace '+' with a standard + operator so that I can evaluate

66 + 88 = 154

Thanks

1
  • can you show what you tried? Commented May 27, 2016 at 11:17

5 Answers 5

3

Use String#split, Array#map it to get Number and then Array#reduce

var value = "66+88";
var result = value.split('+').map(Number).reduce(function(a, b) {
  return a + b;
}, 0);
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

1

You can use eval for this:

var value = eval("66+88");

But you need to be careful, especially if this string come's from user.

This function will evaluate input string as JavaScript and can damage your other scripts or can be used for hacker attacks.

Use it at your own risk!

3 Comments

You can but the way the OP asked question doesn't make me believe that they would understand the dangers of this way.
@CherryDT What is danger of eval?
That it can execute arbitrary JavaScript. Depending where the OP gets this string from in the first place, this can either cause unexpected behavior or more serious XSS issues.
0

Use String#replace

var value = "66+88";
var result = value.replace(/^(\d+)\+(\d+)$/, function(x, y, z){
             return parseInt(y) + parseInt(z) })
console.log(result);

Comments

0

You can use split() method to split the string.

var value = "66+88";
var no = value.split('+');
console.log(parseInt(no[0]) + parseInt(no[1]));

split() method will return an array. In this case

no = ['66','88']

parseInt() will convert string to Int and you can calculate the sum.

Thanks!

Comments

0

You could use split and reduce to sum up your string.

Here is an example.

var value1 = "66+88";
var value2 = "66+88+44";


function sumUpStr (strToSum) {
  var sum = strToSum.split("+").reduce(function(prev, next) {
    return +prev + +next;
  });
  return sum;
};


console.log("Sum of value1 is: " + sumUpStr(value1));
console.log("Sum of value2 is: " + sumUpStr(value2));
console.log("Sum of value1 + value2 is: " + sumUpStr(value1 + "+" + value2));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.