Split a String only on the First Instance of a Character


Borislav Hadzhiev

Mon Oct 04 20211 min read


Photo by Avi Richards

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

To split a JavaScript string only on the first instance 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.

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, add a polyfill or use babel to transpile your code to an older version of JavaScript.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee