Siunami
Siunami

Reputation: 427

Adding numbers within a string

I want to take a string of numbers and characters and add up the numbers.

For example: "In 2015, I want to know how much does iPhone 6+ cost?"

Output: 2021

Here is my current code:

var str = "In 2015, I want to know how much does iPhone 6+ cost?";

function sumFromString(str){
  var punctuationless = str.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?@\[\\\]\^_`{|}~']/g,"");
  var finalString = punctuationless.replace(/\s{2,}/g," ");
  var StringList = finalString.split(" ");
  var sum = [];
  for (i = 0; i < StringList.length; i++)
    if (isInt(StringList[i])
      sum.add(StringList[i]);
  sum.reduce( (prev, curr) => prev + curr );
}
sumFromString(str);

My code takes a string and strips it of punctuation and then places each individual word/number into the array, StringList.

I can't get the next part to work.

What I tried was to iterate through each value in the array. The if statement is supposed to check if the array element is an integer. If so, it will add the integer to an empty array called sum. I then add all the values of the array, sum, together.

Upvotes: 0

Views: 131

Answers (3)

devlin carnate
devlin carnate

Reputation: 8622

For the sake of variety, here's a way to do it without regular expressions:

var myString = "5 bunnies ate 6 carrots in 2days.";
var myArray = myString.split('');
var total = 0;
for (var i = 0; i < myArray.length; i++) {
  if (!isNaN(parseInt(myArray[i]))) {
    total += parseInt(myArray[i]);
  }
}

Fiddle Demo

note: If there's a chance myString could be null, you'd want to add a check before the split.

Upvotes: 1

Richard Hamilton
Richard Hamilton

Reputation: 26444

Split the string into an array of all characters with the split function and then run the filter function to get all numbers. Use the map function to go through all elements that include numbers, and delete characters from them that aren't digits.

Then use reduce to get the sum of all numbers. Since we're dealing with strings here, we have to perform type conversion to turn them into numbers.

string.split(' ').filter(function(word) {
    return /\d+/.test(word) }
}).map(function(s) {
    return s.replace(/\D/, '')
}).reduce(function(a,b) {
    return Number(a) + Number(b);
});

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

Much simpler:

function sumFromString(str) {
    return (str.match(/\d+/g)||[]).reduce((p,c)=>+c+p);
}

Note in particular that I use +c+p - +c casting the current value from a string to a number, then adding it to p. This matches all the numbers in the string - getting an empty array if there were none - and reduces that.

Upvotes: 3

Related Questions