How to turn words into whole numbers JavaScript?

We need to write a function that takes a string of number words as input and converts them into their equivalent whole number.

Problem Overview

Given a string containing number words separated by spaces, we want to convert each word to its corresponding digit and combine them into a single number.

"one five seven eight"  -------> 1578
"two eight eight eight" -------> 2888

Approach

The solution involves creating a mapping of number words to digits, then iterating through each word to build the final number. We split the input string by whitespace and use array methods to process each word.

Example Implementation

const wordToNum = (str) => {
    const legend = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
    return str.toLowerCase().split(" ").reduce((acc, val) => {
        const index = legend.indexOf(val);
        return (acc * 10 + index);
    }, 0);
};

console.log(wordToNum('one five six eight'));
console.log(wordToNum('zero zero two zero eight'));
console.log(wordToNum('eight six seven five'));
1568
208
8675

How It Works

The function uses a legend array where each number word's position corresponds to its digit value. The reduce() method processes each word:

  • acc * 10 shifts the accumulated number left by one decimal place
  • + index adds the current digit to the ones place
  • toLowerCase() ensures case-insensitive matching

Enhanced Version with Error Handling

const wordToNumSafe = (str) => {
    const legend = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
    
    return str.toLowerCase().split(" ").reduce((acc, val) => {
        const index = legend.indexOf(val);
        if (index === -1) {
            console.log(`Warning: "${val}" is not a valid number word`);
            return acc; // Skip invalid words
        }
        return (acc * 10 + index);
    }, 0);
};

console.log(wordToNumSafe('three seven two'));
console.log(wordToNumSafe('one invalid four')); // Demonstrates error handling
372
Warning: "invalid" is not a valid number word
14

Conclusion

Converting number words to integers is achieved by mapping words to their digit values and using array methods to build the final number. The reduce() method efficiently accumulates digits by multiplying by 10 and adding each new digit.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements