How to Split a String Over Only the First Occurrence in JavaScript
In JavaScript, we can split a string over some delimiter using split()
.
How can we split only over the first occurrence of the delimiter?
Using split()
and join()
Suppose we run split()
on a string.
const str = "This is a string";
str.split(" ");
This outputs the following string array:
["This", "is", "a", "string"]
What if we want the string after only the first occurrence?
"is a string"
With slice()
We can split over only the first occurrence of the delimiter using slice()
and join()
.
const str = "This is a string";
str.split(" ").slice(1).join(" "); // "is a string"
slice(1)
will remove the first element of the array.join(delimiter)
will concatenate all elements of the array by the delimiter
With the spread operator ...
Another solution that might be more readable involves using the spread operator.
const str = "This is a string";
const [first, ...rest] = str.split(" ");
rest.join(" "); // "is a string"
Using substring()
and indexOf()
We can also avoid split()
entirely and use substring()
to achieve the same results.
const str = "This is a string";
str.substring(str.indexOf(" ") + 1); // "is a string"
indexOf(delimiter)
will return the index of the first occurrence of the delimitersubstring(index)
will return the substring fromindex
until the end.