
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Validating a String with Numbers in JavaScript
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 −
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
Advertisements