Split string into groups - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Given a string S which consists 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.


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;
         numbers += val;
      }else if(val.toUpperCase() !== val.toLowerCase()){
         alpha += val;
         special += val;
      return { numbers, alpha, special };
      }, {
         numbers: '',
         alpha: '',
         special: ''


Following is the output in the console −

   numbers: '115',
   alpha: 'ThsStringCntnsdfferentchractrs',
   special: '!  0@  @'
Published on 15-Sep-2020 15:07:43