Filtering out numerals from string in JavaScript


Problem

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 −

const output = '1234567';

Example

Following is the code −

 Live Demo

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));

Output

Following is the console output −

1234567

Updated on: 21-Apr-2021

77 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements