Splitting string into groups – JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Given a string S, consisting of alphabets, numbers and special characters. We need to write a program to split the strings in three different strings S1, S2 and S3, such that −

  • The string S1 will contain all the alphabets present in S,
  • The string S2 will contain all the numbers present in S, and
  • S3 will contain all special characters present in S.

The strings S1, S2 and S3 should have characters in the same order as they appear in input.

Example

Following is the code −

const str = "Th!s String C0nt@1ns d1fferent ch@ract5rs";
const seperateCharacters = str => {
   const strArr = str.split("");
   return strArr.reduce((acc, val) => {
      let { numbers, alpha, special } = acc;
      if(+val){
         numbers += val;
      }else if(val.toUpperCase() !== val.toLowerCase()){
         alpha += val;
      }else{
         special += val;
      };
      return { numbers, alpha, special };
   }, {
      numbers: '',
      alpha: '',
      special: ''
   });
};
console.log(seperateCharacters(str));

Output

This will produce the following output in console −

{
   numbers: '115',
   alpha: 'ThsStringCntnsdfferentchractrs',
   special: '!  0@  @'
}
raja
Published on 30-Sep-2020 14:13:58
Advertisements