Summing numbers present in a string separated by spaces using JavaScript

We are required to write a JavaScript function that takes in a string which has integers inside it separated by spaces.

The task of our function is to convert each integer in the string into an integer and return their sum.

Problem

Given a string containing numbers separated by spaces, we need to:

  • Split the string into individual number strings
  • Convert each string to a number
  • Calculate the sum of all numbers

Method 1: Using split() and reduce()

const str = '1 5 12 76 2';

const sumStringNumbers = (str = '') => {
    const sum = str
        .split(' ')
        .map(Number)
        .reduce((acc, val) => acc + val, 0);
    return sum;
};

console.log(sumStringNumbers(str));
96

Method 2: Using for...of Loop

const str = '1 5 12 76 2';

const sumStringNumbers = (str = '') => {
    let sum = 0;
    const numbers = str.split(' ');
    
    for (const num of numbers) {
        sum += Number(num);
    }
    
    return sum;
};

console.log(sumStringNumbers(str));
96

Method 3: Using parseInt() with forEach()

const str = '1 5 12 76 2';

const sumStringNumbers = (str = '') => {
    let sum = 0;
    
    str.split(' ').forEach(numStr => {
        sum += parseInt(numStr, 10);
    });
    
    return sum;
};

console.log(sumStringNumbers(str));
96

How It Works

The solution breaks down into these steps:

  1. split(' ') converts the string into an array of number strings
  2. map(Number) or parseInt() converts each string to a number
  3. reduce() or a loop accumulates the sum

Comparison

Method Readability Performance Lines of Code
split() + reduce() High Good Minimal
for...of loop Medium Best More
forEach() Medium Good Medium

Edge Cases

// Empty string
console.log(sumStringNumbers(''));  // 0

// Single number
console.log(sumStringNumbers('42'));  // 42

// Negative numbers
console.log(sumStringNumbers('-5 10 -3'));  // 2
0
42
2

Conclusion

The split() and reduce() approach provides the most concise solution for summing space-separated numbers in a string. Choose the for...of loop for better performance with large datasets.

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

692 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements