Validating a string with numbers present in it in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string str. Our function should validate the alphabets in the string based on the numbers before them.

We need to split the string by the numbers, and then compare the numbers with the number of characters in the following substring. If they all match, the string is valid and we should return true, false otherwise.

For example −

5hello4from2me

should return true

Because when split by numbers, the string becomes ‘hello’, ‘from’, ‘me’ and all these strings are of same length as the number before them

Example

Following is the code −

 Live Demo

const str = '5hello4from2me';
const validateString = (str = '') => {
   const lenArray = [];
   let temp = '';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(+el){
         lenArray.push([+el, '']);
      }else{
         const { length: len } = lenArray;
         lenArray[len - 1][1] += el;
      };
   };
   return lenArray.every(sub => sub[0] === sub[1].length);
};
console.log(validateString(str));

Output

Following is the console output −

true
raja
Published on 20-Apr-2021 07:47:51
Advertisements