Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Splitting string into groups – JavaScript
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.
Syntax
const separateCharacters = str => {
return str.split("").reduce((acc, val) => {
// Logic to categorize each character
return acc;
}, { numbers: '', alpha: '', special: '' });
};
Example
The following example demonstrates how to separate a string into alphabets, numbers, and special characters:
const str = "Th!s String C0nt@1ns d1fferent ch@ract5rs";
const separateCharacters = 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(separateCharacters(str));
{
numbers: '0115',
alpha: 'ThsStringCntnsdfferentchractrs',
special: '! @ @'
}
How It Works
The algorithm uses three key techniques to categorize characters:
-
Number Detection: Uses
+valto check if a character converts to a truthy number -
Alphabet Detection: Compares
val.toUpperCase() !== val.toLowerCase()to identify letters - Special Characters: Everything else falls into this category (spaces, symbols, punctuation)
Alternative Approach Using Regular Expressions
const str = "Hello123!@# World456$%^";
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: 'HelloWorld',
numbers: '123456',
special: '!@# $%^'
}
Comparison
| Method | Performance | Readability | Flexibility |
|---|---|---|---|
| Reduce with conditionals | Good | Medium | High |
| Regular expressions | Excellent | High | Medium |
Conclusion
Both approaches effectively separate strings into alphabets, numbers, and special characters while maintaining order. The reduce method offers more control, while regex provides cleaner, more concise code for simple categorization tasks.
Advertisements
