How to get value after the last slash in URL with JavaScript
You can retrieve the value after the last slash "/" in a URL using JavaScript through various methods. Here are a few potential solutions.
const url = "https://geekrainian.com/a/b/c/d";
const parts = url.split("/");
const valueAfterSlash = parts[parts.length - 1];
console.log(valueAfterSlash); // Output: "d"
const url = "https://geekrainian.com/a/b/c/d";
const lastSlashIndex = url.lastIndexOf("/");
const valueAfterLastSlash = url.substring(lastSlashIndex + 1);
console.log(valueAfterLastSlash); // Output: "d"
const url = "https://geekrainian.com/a/b/c/d";
const regex = /\/([^/]+)$/; // matches the last slash and captures the text after it
const match = url.match(regex);
const valueAfterLastSlash = match ? match[1] : null;
console.log(valueAfterLastSlash); // Output: "d"
const url = "https://geekrainian.com/a/b/c/d";
const urlObject = new URL(url);
const valueAfterLastSlash = urlObject.pathname.split("/").pop();
console.log(valueAfterLastSlash); // Output: "d"
If your URL ends with a trailing slash without a value (e.g., https://geekrainian.com/a/b/c/d/
), you can still fix it using the methods mentioned above. Here's how you can handle such cases for each method.
const url = "https://geekrainian.com/a/b/c/d/";
const parts = url.split("/");
const lastPart = parts[parts.length - 1];
const valueAfterLastSlash = lastPart === "" ? parts[parts.length - 2] : lastPart;
console.log(valueAfterLastSlash); // Output: "d"
const url = "https://geekrainian.com/a/b/c/d/";
const lastSlashIndex = url.lastIndexOf("/");
const valueAfterLastSlash = lastSlashIndex === url.length - 1
? url.substring(url.lastIndexOf("/", url.length - 2) + 1, url.length - 1)
: url.substring(lastSlashIndex + 1);
console.log(valueAfterLastSlash); // Output: "d"
const url = "https://geekrainian.com/a/b/c/d/";
const regex = /\/([^/]+)\/?$/; // matches the last slash and captures the text after it (ignoring any trailing slashes)
const match = url.match(regex);
const valueAfterLastSlash = match ? match[1] : null;
console.log(valueAfterLastSlash); // Output: "d"
const url = "https://geekrainian.com/a/b/c/d/";
const urlObject = new URL(url);
const pathParts = urlObject.pathname.split("/").filter(part => part !== ""); // remove empty parts (trailing slash)
const valueAfterLastSlash = pathParts[pathParts.length - 1];
console.log(valueAfterLastSlash); // Output: "d"
All of these solutions will provide you with the value after the last slash in the URL. But you might be wondering which method is better?
I recommend using the URL
object since it is specifically designed to work with URLs and can handle some edge cases, such as:
- Double slash in the string
https://geekrainian.com/a/b/c//
- Presence of a query string
https://geekrainian.com/a/b/c/d/?a=b&c=d
- Presence of a fragment
https://geekrainian.com/a/b/c/d#test"
Enjoyed the story? 🤔
If this article was useful for you, please consider supporting me by making a donation.