Skip to content

Instantly share code, notes, and snippets.

@hoanbka
Created March 1, 2017 06:50
Show Gist options
  • Save hoanbka/075162300b0f3515fabbfcd714042b08 to your computer and use it in GitHub Desktop.
Save hoanbka/075162300b0f3515fabbfcd714042b08 to your computer and use it in GitHub Desktop.
Sum of numbers in a string
/**
* Created by Albert Hoan on 2/27/2017.
*/
//input: str = '123abc4xyz' => output: sum=123+4=127
//input: str= '1abc34' => output= 35;
function decodeNumber(str) {
var arr = [];
var res = '';
var len = str.length - 1;
for (var i = 0; i <= len; i++) {
if (!isNaN(str.charAt(i))) {
res = res + str.charAt(i);
if (i == len) {
arr.push(parseInt(res));
}
} else {
if (i <= len && (res.length !== 0)) {
arr.push(parseInt(res));
res = '';
}
}
}
return arr.length !== 0 ? arr.reduce(function(a, b) {
return a + b;
}) : 0;
}
var str = '1sdsd343a';
var str2 = '1abc123';
var str3 = 'abc';
console.log(decodeNumber(str));
console.log(decodeNumber(str2));
console.log(decodeNumber(str3));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment