Split on the Last Occurrence of a String in JavaScript

avatar

Borislav Hadzhiev

Thu Nov 18 20212 min read

Split on the Last Occurrence of a String #

To split a string on the last occurrence of a substring:, use the lastIndexOf() method to get the last index of the substring and call the slice() method on the string to get the portions before and after the substring you want to split on.

index.js
const str = 'one#two#three'; const lastIndex = str.lastIndexOf('#'); const before = str.slice(0, lastIndex); console.log(before); // ๐Ÿ‘‰๏ธ "one#two" const after = str.slice(lastIndex + 1); console.log(after); // ๐Ÿ‘‰๏ธ "three"

We used the String.lastIndexOf method to get the index of the last occurrence of a hash in the string.

The lastIndexOf method returns the index of the last occurrence of the provided substring in the string or -1 if the substring is not contained in the string.

The next step is to use the String.slice method to get the substrings before and after the last index.

We passed the following 2 parameters to the slice method:

  1. start index - the index of the first character to be included in the new string
  2. end index - go up to, but not including this index

To get the substring before the last occurrence, we called the slice method with a start index of 0 and went up to, but not including the index of the last occurrence.

To get the substring after the last occurrence, we called the slice() method with a single parameter - the start index.

Because we don't want to include the hash in the string, we added 1 to the start index.

When you pass a single parameter to the slice method it includes the characters to the end of the string.

If you need to handle a scenario where the substring is not contained in the string, you can use an if statement.
index.js
const str = 'one#two#three'; const lastIndex = str.lastIndexOf('#'); let before = ''; let after = ''; if (lastIndex !== -1) { before = str.slice(0, lastIndex); after = str.slice(lastIndex + 1); } console.log(before); // ๐Ÿ‘‰๏ธ "one#two" console.log(after); // ๐Ÿ‘‰๏ธ "three"

Our if statement checks if the lastIndexOf method didn't return -1.

If it didn't, then the substring is contained in the string and we can safely call the slice method.

Otherwise, the before and after variables would store empty strings.

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