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
Possible to split a string with separator after every word in JavaScript
To split a string with separator after every word, you can use the split() method combined with filter() to remove empty elements that may result from consecutive separators.
Syntax
let result = string.split('separator').filter(value => value);
Basic Example
Let's start with a string that has separators between words:
let sentence = "-My-Name-is-John-Smith-I-live-in-US";
console.log("Original string:", sentence);
let result = sentence.split('-').filter(value => value);
console.log("After split():");
console.log(result);
Original string: -My-Name-is-John-Smith-I-live-in-US After split(): [ 'My', 'Name', 'is', 'John', 'Smith', 'I', 'live', 'in', 'US' ]
How It Works
The split('-') method creates an array by breaking the string at each hyphen. Since our string starts with a hyphen, the first element would be an empty string. The filter(value => value) removes these empty elements:
let text = "-Hello-World-";
console.log("Without filter:", text.split('-'));
console.log("With filter:", text.split('-').filter(value => value));
Without filter: [ '', 'Hello', 'World', '' ] With filter: [ 'Hello', 'World' ]
Different Separators
This technique works with any separator character:
// Using comma separator
let csvData = "apple,banana,orange,grape";
console.log("CSV split:", csvData.split(','));
// Using pipe separator
let pipeData = "red|green|blue|yellow";
console.log("Pipe split:", pipeData.split('|'));
// Using space separator
let spaceData = "one two three four";
console.log("Space split:", spaceData.split(' '));
CSV split: [ 'apple', 'banana', 'orange', 'grape' ] Pipe split: [ 'red', 'green', 'blue', 'yellow' ] Space split: [ 'one', 'two', 'three', 'four' ]
Handling Multiple Consecutive Separators
When dealing with multiple consecutive separators, filter() becomes essential:
let messyString = "--word1---word2--word3-";
console.log("Messy string:", messyString);
console.log("Split result:", messyString.split('-').filter(value => value));
Messy string: --word1---word2--word3- Split result: [ 'word1', 'word2', 'word3' ]
Conclusion
Use string.split('separator').filter(value => value) to split strings and automatically remove empty elements. This approach handles edge cases like leading, trailing, or consecutive separators effectively.
