Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Split string into groups - JavaScript
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.
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
Following is the output in the console −
{
numbers: '115',
alpha: 'ThsStringCntnsdfferentchractrs',
special: '! 0@ @'
}Advertisements