Computer >> Computer tutorials >  >> Programming >> Javascript

Pick out numbers from a string in JavaScript


We are required to write a JavaScript function that takes in a string that might contain some numbers embedded inside it.

The function should extract all the numbers from the string return the new number.

Note − If the string contains no numbers, the function should return 0.

Example

Following is the code −

const str = 'sfsd8fsdf6dsfsd8sdfs28fd0';
const pickNumbers = (str = '') => {
   let res = 0;
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(+el){
         res = (res * 10) + +el;
      };
   };
   return res;
};
console.log(pickNumbers(str));
console.log(pickNumbers('this string contains no numbers'));

Output

Following is the output on console −

86828
0