How to Get the Last Part of a URL in JavaScript

To get the last part of a URL in JavaScript, use .split('/') to split the URL string into an array of each part, then use .at(-1) to get the last part from the array.

For example:

function getLastPart(url) { const parts = url.split('/'); return; } const url1 = ''; console.log(getLastPart(url1)); // javascript-get-last-part-of-url const url2 = ''; console.log(getLastPart(url2)); // blog const url3 = ''; console.log(getLastPart(url3)); //

The Array split() method takes a character and splits a string into an array of substrings that were separated by that character in the string. A URL’s segments are separated by the / character, so we pass this character to split() to create an array with each URL segment as an element.

console.log('123-456-7890'.split('-')); // [ '123', '456', '7890' ] /* [ 'https:', '', '', 'blog', 'javascript-get-last-part-of-url' ] */ console.log( ''.split('/') );

After getting this array, we use the Array at() method to get a single element from it. at() is a new ES2022 addition that accepts both positive and negative integers.

Passing negative integers to at() makes it count from the end of the array, so -1 gives the first element from the end (last element) – the last part of the URL.

const urlParts = [ 'https:', '', '', 'blog', 'javascript-get-last-part-of-url', ]; console.log(; // javascript-get-last-part-of-url console.log(; // blog console.log(; //

Remove last part of URL

You might be getting the last part of the URL to remove it from the URL string. If that’s what you want, there’s no need to get the last part of the URL at all – we can remove it easily with the slice() and lastIndexOf() methods.

function removeLastPart(url) { return url.slice(0, url.lastIndexOf('/')) } const url1 = ''; // console.log(removeLastPart(url1)); const url2 = ''; // console.log(removeLastPart(url2));

We use the String lastIndexOf() method to get the position of the last occurrence of the / character, because this is the point just before the last part of the URL starts in the string.

String slice() returns the portion of a string between specified start and end indexes, passed as the first and second arguments respectively. We pass 0 as the first argument so the resulting substring starts from the first character, and we pass the result of lastIndexOf() as the second argument so that the substring ends at the index before the last part of the URL starts in the string.

Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *