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
Splitting strings based on multiple separators - JavaScript
We are required to write a JavaScript function that takes in a string and any number of characters specified as separators. Our function should return a splitted array of the string based on all the separators specified.
For example, if the string is:
const str = 'rttt.trt/trfd/trtr,tr';
And the separators are:
const sep = ['/', '.', ','];
Then the output should be:
const output = ['rttt', 'trt', 'trfd', 'trtr'];
Method 1: Using Manual Iteration
This approach manually iterates through each character and checks if it matches any of the separators:
const str = 'rttt.trt/trfd/trtr,tr';
const splitMultiple = (str, ...separator) => {
const res = [];
let start = 0;
for(let i = 0; i
['rttt', 'trt', 'trfd', 'trtr', 'tr']
Method 2: Using Regular Expression (Recommended)
A more concise approach using regular expressions with character classes:
const str = 'rttt.trt/trfd/trtr,tr';
const splitMultipleRegex = (str, ...separators) => {
// Escape special regex characters and join with |
const escapedSeparators = separators.map(sep =>
sep.replace(/[.*+?^${}()|[\]\]/g, '\$&')
);
const regex = new RegExp(`[${escapedSeparators.join('')}]`);
return str.split(regex).filter(part => part.length > 0);
};
console.log(splitMultipleRegex(str, '/', '.', ','));
['rttt', 'trt', 'trfd', 'trtr', 'tr']
Method 3: Using reduce() for Multiple split() Calls
This approach applies split() sequentially for each separator:
const str = 'rttt.trt/trfd/trtr,tr';
const splitMultipleReduce = (str, ...separators) => {
return separators.reduce((acc, separator) => {
return acc.flatMap(part => part.split(separator));
}, [str]).filter(part => part.length > 0);
};
console.log(splitMultipleReduce(str, '/', '.', ','));
['rttt', 'trt', 'trfd', 'trtr', 'tr']
Comparison
| Method | Performance | Readability | Handles Special Characters |
|---|---|---|---|
| Manual Iteration | Fast | Medium | Yes |
| Regular Expression | Medium | High | Yes (with escaping) |
| reduce() with split() | Slow | High | Yes |
Conclusion
The regular expression method is recommended for most use cases due to its balance of readability and performance. Use manual iteration for performance-critical applications or when working with very large strings.
