Split string into groups - JavaScript

Given a string that consists of alphabets, numbers, and special characters, we need to split it into three separate strings based on character type.

We'll create three strings where:

  • S1 contains all alphabets from the original string
  • S2 contains all numbers from the original string
  • S3 contains all special characters from the original string

The characters in each resulting string maintain the same order as they appear in the input string.

Example Implementation

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));
{
   numbers: '0115',
   alpha: 'ThsStringCntnsdfferentchractrs',
   special: '! @  @'
}

How It Works

The function uses these detection methods:

  • Numbers: Uses +val to check if the character converts to a truthy number
  • Alphabets: Compares toUpperCase() and toLowerCase() - alphabets will differ, non-alphabets won't
  • Special characters: Everything else (spaces, punctuation, symbols)

Alternative Approach Using Regular Expressions

const str = "Th!s String C0nt@1ns d1fferent ch@ract5rs";

const separateWithRegex = str => {
   return {
      alpha: str.replace(/[^a-zA-Z]/g, ''),
      numbers: str.replace(/[^0-9]/g, ''),
      special: str.replace(/[a-zA-Z0-9]/g, '')
   };
};

console.log(separateWithRegex(str));
{
   alpha: 'ThsStringCntnsdfferentchractrs',
   numbers: '0115',
   special: '! @  @'
}

Comparison

Method Performance Readability Flexibility
reduce() with type checking Good Moderate High
Regular expressions Very Good High Moderate

Conclusion

Both approaches effectively separate strings by character type while preserving order. The regex method is more concise and readable for simple character classification tasks.

Updated on: 2026-03-15T23:18:59+05:30

317 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements