Skip to content
Sum of Numbers in a String - JS

Sum of Numbers in a String – JS

🟢 Easy 🧩 Pattern – Strings, Regex and Loops

From the given string of Characters (can be a mix of numbers, alphabets, and other special characters), we need to find the sum of all numbers in the string.

Examples

Input: Ma1rix13ead
Output: 14  [1+13]

Input: Abhi12xyz3pq4
Output: 19  [12+3+4]Code language: JavaScript (javascript)

JS Solution

function sumOfNumbersInString(str) {
    // Regular expression to match all numbers in the string
    const numbers = str.match(/\d+/g);
    // If no numbers are found
    if (!numbers) return 0;
    // Convert each number to an integer and calculate the sum
    const sum = numbers.reduce((acc, num) => acc + parseInt(num), 0);
    return sum;
}

const input = "Today is the 5th of August 2025";
console.log(sumOfNumbersInString(input)); // Output: 2030Code language: JavaScript (javascript)
Back to Top