Borislav Hadzhiev
Reading timeยท2 min
Photo from Unsplash
Use the String.split()
method with array destructuring to split a string
only on the first occurrence of a character, e.g.
const [first, ...rest] = str.split('-');
.
The array destructuring syntax will capture the two parts 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
We used the
String.split
method to split the string on a hyphen (-
).
We used
array destructuring assignment
to assign the first element of the array to the first
variable.
rest
variable, we used both array destructuring and the rest operator to gather all of the remaining elements of the array into therest
variable.At this point, the rest
variable is an array containing 2 elements -
['again', 'later']
.
Lastly, we used the
Array.join
method to join the contents of the rest
array with a hyphen and to get the
remainder of the string - again-later
.
Alternatively, you can use the slice
method.
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.
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.
1
to its index to start immediately after.The second example shows how to get the part before the first occurrence of the character.
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.