Filtering out numerals from string in JavaScript

We are required to write a JavaScript function that takes in a string, str, which contains a combination of alphabets, special characters and numbers.

Our function should return a new string based on the input string that contains only the numbers present in the string str, maintaining their relative order.

For example, if the input to the function is:

const str = 'revd1fdfdfs2v34fd5gfgfd6gffg7ds';

Then the output should be:

'1234567'

Using for Loop and Type Coercion

This approach iterates through each character and uses the unary plus operator (+) to check if the character is a number:

const str = 'revd1fdfdfs2v34fd5gfgfd6gffg7ds';
const pickNumbers = (str = '') => {
    let res = '';
    for(let i = 0; i < str.length; i++){
        const el = str[i];
        if(+el){
            res += el;
        };
    };
    return res;
};
console.log(pickNumbers(str));
1234567

Using Regular Expression

A more concise approach using regex to match all digits and join them:

const str = 'revd1fdfdfs2v34fd5gfgfd6gffg7ds';
const pickNumbers = (str = '') => {
    return str.match(/\d/g)?.join('') || '';
};
console.log(pickNumbers(str));
1234567

Using Array Filter and isNaN

This method converts the string to an array, filters numeric characters, and joins them back:

const str = 'revd1fdfdfs2v34fd5gfgfd6gffg7ds';
const pickNumbers = (str = '') => {
    return str.split('').filter(char => !isNaN(char) && char !== ' ').join('');
};
console.log(pickNumbers(str));
1234567

Comparison

Method Performance Readability Browser Support
for Loop + Type Coercion Fast Good All browsers
Regular Expression Medium Excellent All browsers
Array Filter Slower Good Modern browsers

Edge Cases

Handle strings with no numbers or empty strings:

console.log(pickNumbers('abc'));     // Empty string
console.log(pickNumbers(''));        // Empty string
console.log(pickNumbers('123'));     // All numbers

123

Conclusion

The regular expression method offers the most concise solution, while the for loop approach provides better performance for large strings. Choose based on your specific requirements for readability versus performance.

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

222 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements