JavaScript String

let str=‘1 1 1 1 1 1’;

if I wanted to add up those numbers which are now strings, how can I do that?

You would need to split the string into an array.

you could use str.split(" ")

then use a for loop to add the array of split items

https://www.w3schools.com/jsref/jsref_split.asp

There is space in between those numbers which becomes problem while looping.

I try this way but it’s not working…

let add='1 1 1 1 1 1';

let result=add.split('');

let final=newOne.reduce(function(a,b){
  return a+b;
})
let result=add.split(' ');

did you forgot to add the whitespace in your split function :wink:

There two other mistakes: newOne should be result and you need to do parseInt, since it is still a string.

I know what you mean but I wanted to sum up but it’s not working…That’s the problem…have a look again…

 let add='1 1 1 1 1 1';
 
let result=add.split(' ');
let final=result.reduce(function(a,b){
  return a+b;
})
   console.log(final); // output is should be 6 instead of 111111;

Look at @DanielSubat’s answer above.

Thanks a lot,finally I got it.