Function that parses number embedded in strings - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Conventionally, we have functions like parseInt() and parseFloat() that takes in a string and converts the number string to Number. But these methods fail when we have numbers embedded at random index inside the string.

For example: The following would only return 454, but what we want is 4545453 −

parseInt('454ffdg54hg53')

So, we are required to write a JavaScript function that takes in such string and returns the corresponding number.

Example

Following is the code −

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

Output

Following is the output in the console −

4545453
raja
Published on 18-Sep-2020 09:47:07
Advertisements