I'm trying to take the string '27 4 2019' and output the sum of 2050. Not in a string.
So far I have split it.
let x = '27 4 2019'
console.log(x.split('').?
I'm not sure how to add the numbers together after splitting it.
I'm trying to take the string '27 4 2019' and output the sum of 2050. Not in a string.
So far I have split it.
let x = '27 4 2019'
console.log(x.split('').?
I'm not sure how to add the numbers together after splitting it.
Split based on whitespace, and reduce
while converting into numbers:
const str = "27 4 2019";
const output = str.split(/\s/).reduce((a, b) => a + parseInt(b), 0);
console.log(output);
You can try to:
String
to array values using a whitespace ' '
as a separator.String
type to Number
.const s = '27 4 2019';
const out = s.split(' ').map(Number).reduce((sum, curr) => sum + curr);
console.log(out);
You can use a RegEx replace
function to iterate through all your numerical elements and add them. +n
acts as an operator to coerce the string to a number, which you know will work because we're only grabbing numerical elements from the string. This also has the added benefit of passing over the string once, where other answers may go through it several times, and it doesn't require coercion of your string to an array.
let total;
string.replace(/[0-9]/g, (n) => total = total ? total + (+n) : +n);
let x = '27 4 2019', total;
x.replace(/[0-9]/g, (n) => total = total ? total + (+n) : +n);
console.log(total);
Another clean solution could be to use regex
to find numbers in a string and pass a supporting function to ad them up as
let x = '27 4 2019', total = 0;
x.replace(/\d+/g, (obj) => total += +obj);
console.log(total);