Function that parses number embedded in strings - JavaScript

JavaScript's built-in functions like parseInt() and parseFloat() only parse numbers from the beginning of a string, stopping when they encounter non-numeric characters. When you need to extract all digits from anywhere within a string, you need a custom solution.

The Problem with Built-in Methods

Standard parsing methods fail with embedded numbers:

console.log(parseInt('454ffdg54hg53'));    // 454 (stops at first non-digit)
console.log(parseFloat('12.34abc56.78'));  // 12.34 (stops at 'a')
454
12.34

Method 1: Loop Through Characters

This approach iterates through each character, extracting only digits:

const numStr = '454ffdg54hg53';

const parseInteger = numStr => {
    let res = 0;
    for(let i = 0; i < numStr.length; i++){
        if(!+numStr[i] && numStr[i] !== '0'){
            continue;
        };
        res = (res * 10) + (+numStr[i]);
    };
    return res;
};

console.log(parseInteger(numStr));
console.log(parseInteger('abc123def456'));
console.log(parseInteger('1a2b3c'));
4545453
123456
123

Method 2: Using Regular Expressions

A more concise approach using regex to extract all digits:

const parseIntegerRegex = str => {
    const digits = str.match(/\d/g);
    return digits ? parseInt(digits.join(''), 10) : 0;
};

console.log(parseIntegerRegex('454ffdg54hg53'));
console.log(parseIntegerRegex('no123numbers456here'));
console.log(parseIntegerRegex('abc'));  // No digits
4545453
123456
0

Method 3: Using Filter and Join

Split the string and filter numeric characters:

const parseIntegerFilter = str => {
    const result = str.split('').filter(char => !isNaN(char) && char !== ' ').join('');
    return result ? parseInt(result, 10) : 0;
};

console.log(parseIntegerFilter('454ffdg54hg53'));
console.log(parseIntegerFilter('price$29.99discount15%'));
4545453
292999915

Comparison

Method Performance Readability Handles Edge Cases
Character Loop Fast Medium Good
Regular Expression Medium High Excellent
Filter Method Slower High Good

Conclusion

For extracting digits from strings, the regex approach offers the best balance of readability and functionality. Use the character loop method when performance is critical for large strings.

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

169 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements