Filtering out numerals from string in JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 21-Apr-2021 11:58:13
Advertisements