Split on the Last Occurrence of a String in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 4, 2024
4 min

banner

# Split on the Last Occurrence of a String in JavaScript

To split a string on the last occurrence of a substring:

  1. Use the lastIndexOf() method to get the last occurrence of the substring.
  2. Use the slice() method to get the parts before and after the substring.
index.js
function splitLastOccurrence(str, substring) { const lastIndex = str.lastIndexOf(substring); const before = str.slice(0, lastIndex); const after = str.slice(lastIndex + 1); return [before, after]; } const str = 'bobby#hadz#com'; const [before, after] = splitLastOccurrence(str, '#'); console.log(before); // ๐Ÿ‘‰๏ธ bobby#hadz console.log(after); // ๐Ÿ‘‰๏ธ com

split on last occurrence of string

The code for this article is available on GitHub

The String.lastIndexOf() method returns the index of the last occurrence of a substring in a string.

The method returns -1 if the substring is not contained in the string.

The String.slice() method extracts a section of a string and returns it, without modifying the original string.

The String.slice() method takes the following arguments:

NameDescription
start indexThe index of the first character to include in the returned substring
end indexThe index of the first character to exclude from the returned substring

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.

index.js
const str = 'bobby#hadz#com'; const lastIndex = str.lastIndexOf('#'); // ๐Ÿ‘‡๏ธ bobby#hadz console.log(str.slice(0, lastIndex));

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

index.js
const str = 'bobby#hadz#com'; const lastIndex = str.lastIndexOf('#'); // ๐Ÿ‘‡๏ธ com console.log(str.slice(lastIndex + 1));

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

When only a single argument is passed to the String.slice() method, the slice goes to the end of the string.

# The substring might not be contained in 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
function splitLastOccurrence(str, substring) { const lastIndex = str.lastIndexOf(substring); let before = ''; let after = ''; if (lastIndex !== -1) { before = str.slice(0, lastIndex); after = str.slice(lastIndex + 1); } return [before, after]; } const str = 'bobby-hadz-com'; const substring = '#'; const [before, after] = splitLastOccurrence(str, substring); console.dir(before); // ๐Ÿ‘‰๏ธ '' console.dir(after); // ๐Ÿ‘‰๏ธ ''

substring might not be contained in the string

The code for this article is available on GitHub

The lastIndexOf() method returns -1 if the substring is not contained in the string.

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.

# Split on the Last Occurrence of a String using split()

This is a three-step process:

  1. Split the string on each occurrence of the substring.
  2. Use the pop() method to get the part after the last occurrence.
  3. Use the join() method to get the part before the last occurrence.
index.js
function splitLastOccurrence(str, substring) { const arr = str.split(substring); const after = arr.pop(); const before = arr.join(substring); return [before, after]; } const str = 'bobby#hadz#com'; const [before, after] = splitLastOccurrence(str, '#'); console.log(before); // ๐Ÿ‘‰๏ธ bobby#hadz console.log(after); // ๐Ÿ‘‰๏ธ com

split on last occurrence of string using split

The code for this article is available on GitHub

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

The String.split() method takes the following 2 parameters:

NameDescription
separatorThe pattern describing where each split should occur.
limitAn integer used to specify a limit on the number of substrings to be included in the array.

We split the string on each occurrence of the substring.

index.js
const str = 'bobby#hadz#com'; // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(str.split('#'));

We used the Array.pop() method to get the part after the last occurrence of the substring.

index.js
const str = 'bobby#hadz#com'; console.log(str.split('#').pop()); // ๐Ÿ‘‰๏ธ com

The pop() method removes and returns the last element from the array.

You can use the join() method to join the remainder of the array with the substring as a separator to get the part before the last occurrence of the substring.

index.js
function splitLastOccurrence(str, substring) { const arr = str.split(substring); const after = arr.pop(); const before = arr.join(substring); return [before, after]; } const str = 'bobby#hadz#com'; const [before, after] = splitLastOccurrence(str, '#'); console.log(before); // ๐Ÿ‘‰๏ธ bobby#hadz console.log(after); // ๐Ÿ‘‰๏ธ com
The code for this article is available on GitHub

The Array.join() method joins an array into a string based on the provided delimiter.

index.js
console.log(['bobby', 'hadz'].join('#')); // ๐Ÿ‘‰๏ธ bobby#hadz

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev