Removing 0s from start and end - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number as a string and returns a new number string with all the leading and trailing 0s removed

For example: If the input is −

const strNum = '054954000'

Then the output should be −

const output = '54954'

Example

Following is the code −

const strNum = '054954000';
const removeZero = (str = '') => {
   const res = '';
   let startLen = 0, endLen = str.length-1;
   while(str[startLen] === '0'){
      startLen++;
   };
   while(str[endLen] === '0'){
      endLen--;
   };
   return str.substring(startLen, endLen+1);
};
console.log(removeZero(strNum));

Output

Following is the output in the console −

54954
raja
Published on 16-Sep-2020 09:38:09
Advertisements