Regrouping characters of a string in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string str as the first and the only argument.

The string str can contain three types of characters −

  • English alphabets: (A-Z), (a-z)

  • Numerals: 0-9

  • Special Characters − All other remaining characters

Our function should iterate through this string and construct an array that consists of exactly three elements, the first contains all alphabets present in the string, second contains the numerals and third the special characters maintain the relative order of characters. We should finally return this array.

For example, if the input to the function is

Input

const str = 'thi!1s is S@me23';

Output

const output = [ 'thisisSme', '123', '! @' ];

Example

Following is the code −

 Live Demo

const str = 'thi!1s is S@me23';
const regroupString = (str = '') => {
   const res = ['', '', ''];
   const alpha = 'abcdefghijklmnopqrstuvwxyz';
   const numerals = '0123456789';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(alpha.includes(el) || alpha.includes(el.toLowerCase())){
         res[0] += el;
         continue;
      };
      if(numerals.includes(el)){
         res[1] += el;
         continue;
      };
      res[2] += el;
   };
   return res;
};
console.log(regroupString(str));

Output

[ 'thisisSme', '123', '! @' ]
raja
Published on 24-Apr-2021 10:34:41
Advertisements