Reputation: 51
I need to count numbers in a string. The numbers are separated by spaces. (1 2 3 4 10) I was trying to do this by charAt by that doesnt work if the number is not a single digit. I am relative new to JS and need some examples. I started with this but ran into a double digit #:
string1 = (1 1 1 4 10)
var total = parseFloat(0);
for(var j=0; j<string1.length; j++) {
total += parseFloat(string1.charAt(j));
}
Any help would be appreciated
Upvotes: 1
Views: 2778
Reputation: 3
Here's a simpler way. First, fix string1 so it's actually a string (by adding " "s), also properly declare it with "var string". Then you could do something like this.
var string1 = ("1 1 1 4 10")
function addString(input) {
var sum = 0; //get your empty variable ready
var array1 = input.split(" "); //split your string into an array
for(var i=0; i<array1.length; i++) {
array1[i] = parseInt(array1[i]); // each new array element is integer
sum += array1[i]; // += is operator for solve/refactor
}
return sum;
}
addString(string1);
Upvotes: 0
Reputation: 5039
// use method split to convert string to array and then add array items:
var string1 = "1 1 1 4 10", total = 0;
string1.split(" ").forEach(function(item) {
total += +item;
});
Upvotes: 0
Reputation: 138257
Create an array:
var arr=[1,2,3]
and then do:
var count=0;
arr.forEach(function(number){
count+=number;
}
Or use a string:
var str="1 2 3";
var arr=str.split(" ");
var count=0;
arr.forEach(function(number){
count+=parseInt(number);
}
Count now contains the sum of all chars
Upvotes: 0
Reputation: 4783
I don't know why you need to do this way, but if this string comes from another font, you can deal with it, something like this:
var string1 = "(1 1 1 4 10)";
var aux = string1.replace("(","").replace(")","");
aux = aux.split(" ");
var total = parseFloat(0);
for(var j=0; j<aux.length; j++) {
total += parseFloat(aux[j]);
}
console.log(total);
https://jsfiddle.net/bggLkvxd/1/
Upvotes: 1