How to extract the last part of a JavaScript url?
The split() method first splits the url into an array of elements separated by the / method then pop() helps us get the last element of an array (which is our last url segment). Similarly, we can also get the last segment using the combination of the substring() and lastIndexOf() methods.
Table of Contents
Where is the last slash in the URL?
13 answers
- url.rsplit(‘/’, 1) returns a list, and url.rsplit(‘/’, 1)[-1] is the bit after the last forward slash. –
- Another way to do it would be: url.rsplit(‘/’, 1).pop() – Alex Fortin Mar 2 ’15 at 15:00
- @MitchMcMabers please turn this into an answer (which should then be the accepted one) – Caterpillaraoz Feb 19 at 18:05.
How to get path from JavaScript url?
- window.location.pathname.split(‘/’); it’s a more elegant solution in most cases if you’re trying to access the different sections of the URL beyond the standard protocol and www etc. –
- window.location.pathname.split(‘/’).filter(function(v) { return v; }); will remove empty elements for Javascript 1.6 and above. –
How to get url and its parts in JavaScript?
Get URLs and URL parts in JavaScript
- window.location.protocol = “http:”
- window.location.host = “css-tricks.com”
- window.location.pathname = “/example/index.html”
- window.location.search = “? s=flexible box”
How do I get a URL?
Answer: Use the window. Location. href Location of the property. href to get the full URL of the current page including hostname, query string, fragment id, etc. The following example will display the current URL of the page when the button is clicked.
How to get last URL segment in JavaScript?
In this tutorial, we are going to learn how to get the last segment of a URL or path using JavaScript. Consider, we have the following URL: To get the playlist of the last segment from a previous URL, we can use the split() method by passing a / as an argument and we need to call the pop() method on it.
How to get the base URL in JavaScript?
If you want to get the base URL (http://www.example.com/something/) from any URL, use these two lines of code: var re = new RegExp(/^.*////); return re.exec(window.location.href); Additional explanation and full functions to copy/paste here: Javascript: Get Base URL or Root URL
How to get the current URL with JavaScript?
Learn how to get the current URL with JavaScript. Current URL Use window.location.href to get the current URL: Example document.getElementById(“demo”).innerHTML = “The full URL of this page is: ” + window.location.href;
How to find the last occurrence of a character in a URL?
You can also use the lastIndexOf() function to locate the last occurrence of the character / in your URL, then the substring() function to return the substring starting at that location: That way you avoid creating an array containing all your Segments. URL, as split() does.