Split a String only on the First Occurrence of a Character

avatar

Borislav Hadzhiev

Sat Nov 13 20212 min read

banner

Photo by Avi Richards

Updated - Sat Nov 13 2021

Split a String only on the First Occurrence of a Character #

To split a JavaScript string only on the first occurrence of a character, use the String.split() method with array destructuring to capture the first part and the remainder of the string in separate variables, e.g. const [first, ...rest] = str.split('-').

index.js
const str = 'try-again-later'; const [first, ...rest] = str.split('-'); console.log(first); // 👉️ try console.log(rest); // 👉️ ['again', 'later'] const remainder = rest.join('-'); console.log(remainder); // 👉️ again-later

In the code snippet, we've used the String.split method to split the string on a dash (-).

We use array destructuring assignment to assign the first element of the array to the first variable.

For the rest variable, we use both array destructuring and the rest operator to gather all of the remaining elements of the array into the rest variable.

At this point the rest variable is an array containing 2 elements - ['again', 'later'].

Finally we use the Array.join method to join the contents of the rest array on a dash and get the remainder of the string - again-later.

Note that destructuring assignment is not supported in Internet Explorer. If you need to support the browser, use the next approach covered in the article.

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

index.js
// ✅ Supported in IE const str = 'try-again-later'; const after = str.slice(str.indexOf('-') + 1); console.log(after); // 👉️ again-later const before = str.slice(0, str.indexOf('-')); console.log(before); // 👉️ try

The first example shows how to get the part after the last occurrence of a character.

The parameter we passed to the String.slice method is the start index - the index of the first character to be included in the new string.

Because we want to exclude the specified character, we add 1 to its index to start immediately after.

The second example shows how to get the part before the first occurrence of the character.

The second parameter we passed to the slice() method is the end index - go up to, but not including this index.

In this scenario, we start at index 0 and go up to, but not including the index of the first occurrence of the supplied character.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.