Get the Part After Last Occurrence in a String in JavaScript or Node.js

JavaScript’s stdlib for strings contains dozens of methods. These methods are useful in a lot of situations. Yet, there are use cases where a method doesn’t exist in the stdlib.

For situations where you want to retrieve the part of a string after the last occurrence of a given character sequence, you need to build your own utility function. That’s what this tutorial shows you: how to build your own afterLast string utility method.

Node.js Series Overview

Retrieve the String Part After the Last Delimiter Occurrence

JavaScript comes with the String#split method. This split method divides a given string value at each occurrence of a given delimiter. The result is an array of ordered substrings.

The afterLast utility should return the last item in the array of substrings. In case the divided array of substrings contains only one item, it means the delimiter value wasn’t found and you’re returning the original string value.

Here’s a sample afterLast utility function returning the part of a string after the last occurrence of a given character:

/**
 * Returns the portion of the string after the last occurrence of the given `delimiter`.
 *
 * @param {String} delimiter
 *
 * @returns {String}
 */
function afterLast (value, delimiter) {  
  value = value || ''

  return delimiter === ''
      ? value
      : value.split(delimiter).pop()
}

Notice: splitting a string for an empty delimiter creates an array of the string’s characters. That’s why you need to return the original value when receiving an empty string as a delimiter.

Then you can use the afterLast function like this:

afterLast('Future Studio is an awesome island', 'is')  
// 'land'

afterLast('Future Studio is an awesome island', 'great')  
// 'Future Studio is an awesome island'

afterLast('Future Studio')  
// 'Future Studio'

Use the @supercharge/strings Package

I’m the maintainer of the @supercharge/strings package providing convenient string utilities. It provides a useful Str#afterLast method returning the remainder of the string after the last occurrence of a given character or character sequence:

const Str = require('@supercharge/strings')

Str('Future Studio is an awesome island').afterLast('is')  
// 'land'

Str('Future Studio is an awesome island').afterLast('great')  
// 'Future Studio is an awesome island'

Str('Future Studio').afterLast()  
// 'Future Studio'

That’s it!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.