Skip to main content

How to Get the Substring After the Last Occurrence of a Character in JavaScript

A very common string manipulation task is to extract the part of a string that comes after the last occurrence of a specific character or delimiter. This is frequently used to get a filename from a full path, an extension from a filename, or the last segment of a URL.

This guide will teach you the two most effective methods for this task. We'll cover the highly performant and readable approach using lastIndexOf() and slice(), as well as the popular and concise split() and pop() combination.

The Core Problem: Finding the Last Segment

The goal is to find the final occurrence of a delimiter and return the substring that follows it.

For example, how to reliably get the filename "report.pdf" from this path?

// Problem: How to reliably get the filename "report.pdf" from this path?
const filePath = '/users/home/documents/report.pdf';

We need a method that can find the last / and return everything after it.

This is a highly efficient and robust method that avoids creating intermediate arrays. It is generally the recommended best practice, especially for performance-critical code.

The logic:

  1. Use String.prototype.lastIndexOf(char) to find the index of the last occurrence of the delimiter.
  2. Add 1 to this index to get the starting position of the substring that follows the delimiter.
  3. Use String.prototype.slice() with this starting index to extract the rest of the string.

Solution:

function getAfterLast(str, char) {
// Find the index of the last occurrence of the character
const lastIndex = str.lastIndexOf(char);

// Slice the string from the character after the last occurrence to the end
return str.slice(lastIndex + 1);
}

// Example Usage:
const filePath = '/users/home/documents/report.pdf';
const filename = getAfterLast(filePath, '/');
console.log(filename); // Output: "report.pdf"

const domain = 'www.example.com';
const tld = getAfterLast(domain, '.');
console.log(tld); // Output: "com"

The split and pop Method (Simple and Readable)

This method is often very intuitive and easy to write. It splits the string into an array of segments and then simply takes the last one.

The logic:

  1. Use String.prototype.split(char) to break the string into an array of substrings, using the character as the delimiter.
  2. Use Array.prototype.pop() to remove and return the last element of that array.

Solution:

function getAfterLast(str, char) {
return str.split(char).pop();
}

// Example Usage:
const filePath = '/users/home/documents/report.pdf';
const filename = getAfterLast(filePath, '/');
console.log(filename); // Output: "report.pdf"
note

While highly readable, this method is slightly less performant than the slice approach because it has to create an intermediate array of all the parts of the string, which is unnecessary work. For most use cases, this difference is negligible.

What Happens When the Character is Not Found

A robust solution must handle cases where the delimiter does not exist in the string. Both methods handle this gracefully, but with a slight difference in how they arrive at the result.

lastIndexOf and slice

  • lastIndexOf() will return -1.
  • Adding 1 makes the start index 0.
  • str.slice(0) returns the entire original string.
'filename.pdf'.slice('filename.pdf'.lastIndexOf('/') + 1); // Returns 'filename.pdf'

split and pop

  • split() will return an array containing just the original string ['filename.pdf'].
  • .pop() will return the one and only element, which is the entire original string.
'filename.pdf'.split('/').pop(); // Returns 'filename.pdf'
note

Both methods correctly return the original string if the delimiter isn't found, which is usually the desired behavior.

Conclusion

For getting the substring after the last occurrence of a character, JavaScript offers two excellent, concise solutions.

  • The lastIndexOf() and slice() combination is the most performant method, as it avoids creating an intermediate array. It is the recommended best practice for performance-critical applications.
  • The split().pop() chain is often considered highly readable and intuitive. It is a great choice for most day-to-day scripting where absolute performance is not a concern.

Both methods are excellent, and the choice between them often comes down to a preference for performance versus a slightly more declarative style.