Sometimes, we want to split a string only the at the first n occurrences of a delimiter.
In this article, we’ll look at how to split a string only the at the first n occurrences of a delimiter.
Split a String Only the at the First n Occurrences of a Delimiter
To split a string only the at the first n occurrences of a delimiter, we can use the split
method with the JavaScript array’s splice
and join
methods.
For instance, we write:
const string = 'Split this, but not this'
const arr = string.split(' ')
const result = arr.splice(0, 2)
result.push(arr.join(' '));
console.log(result)
We call split
on the whole string
.
Then we call splice
to with 0 and 2 to get the first 2 items from the arr
array and assign it to result
.
The items returned by splice
are removed from arr
.
Next, we call arr.join
with the remaining substrings in the arr
array with a space to join them together.
Finally, we call result.push
on that string to add that string to result
.
Therefore, result
is ['Split', 'this,', 'but not this']
according to the console log.
Conclusion
To split a string only the at the first n occurrences of a delimiter, we can use the split
method with the JavaScript array’s splice
and join
methods.