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

JavaScript’s stdlib for strings comes with a solid foundation. It provides useful methods for common use cases. It can’t provide methods for every use case. Yet, you can build your own utility methods using the existing functionality.

This tutorial shows you how to retrieve the part of a string before the last occurrence of a given delimiter.

Node.js Series Overview

Retrieve the String Part Before the Last Occurrence of a Delimiter

You can use JavaScript’s String#split method to split a given string into the parts that occurred around the character(s) to split on.

Using the array of split parts allows you to retrieve the portion before the last occurrence of a character or character sequence. In this case, you want all parts of the array except the last one.

Here’s a beforeLast utility function returning the part before the last occurrence of a given delimiter:

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

  if (delimiter === '') {
    return value
  }

  const substrings = value.split(delimiter)

  return substrings.length === 1
    ? value // delimiter is not part of the string
    : substrings.slice(0, -1).join(delimiter)
}

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

You’re returning the original string in case the given delimiter doesn’t create a match.

Then you can use the beforeLast function like this:

beforeLast('Future Studio is an awesome island', 'is')  
// 'Future Studio is an awesome '

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

beforeLast('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#beforeLast method returning the part of a string before the last occurrence of the given delimiter:

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

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

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

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

That’s it!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.