Picking all the numbers present in a string in JavaScript

We are required to write a JavaScript function that takes in a string that contains some one-digit numbers in between and the function should return the sum of all the numbers present in the string.

Example

The code for this will be ?

const str = 'uyyudfgdfgf5jgdfj3hbj4hbj3jbb4bbjj3jb5bjjb5bj3';
const sumNum = str => {
    const strArr = str.split("");
    let res = 0;
    for(let i = 0; i < strArr.length; i++){
        if(+strArr[i]){
            res += +strArr[i];
        };
    };
    return res;
};
console.log(sumNum(str));

Output

The output in the console ?

35

How It Works

The function splits the string into individual characters, then checks each character. The unary plus operator (+) converts characters to numbers - it returns 0 for non-numeric characters (which is falsy) and the actual number for digits (which is truthy).

Alternative Method Using Regular Expressions

const str = 'abc7def2ghi9jkl1mn';
const sumWithRegex = str => {
    const numbers = str.match(/\d/g) || [];
    return numbers.reduce((sum, num) => sum + parseInt(num), 0);
};
console.log(sumWithRegex(str));
19

Comparison

Method Readability Performance
Split and Loop Good Faster for short strings
Regular Expression Excellent Better for complex patterns

Conclusion

Both methods effectively extract and sum digits from strings. The split method offers direct control, while regex provides cleaner, more readable code for pattern matching.

Updated on: 2026-03-15T23:19:00+05:30

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements