Last segment of URL with JavaScript
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 from that location:
console.log(this.href.substring(this.href.lastIndexOf('/') + 1));
That way, you'll avoid creating an array containing all your URL segments, as split()
does.
Getting last segment of url
You can use the pathname, search, and/or hash part of the window.location
to do this. Ignore the parser here as it is just used as an example to run this code.
var url = "http://localhost:15043/Maintenance/ModelDetails/3?blah=abc&makeId=14#test";
function parseUrl(url) {
var a = document.createElement("a");
a.href = url;
return a;
}
var parser = parseUrl(url);
var last_segment = parser.pathname.split('/').pop();
var searchParams = parser.search.substring(1).split("&");
var lastParamValue = searchParams[searchParams.length-1].split("=")[1];
var hash = parser.hash;
console.log(last_segment);
console.log(lastParamValue);
console.log(hash);
Getting the last segment of an URL
https://developer.mozilla.org/en-US/docs/Web/API/URL
const getLastPath = (url) => {
url = new URL(url);
const pathname = url.pathname;
const paths = pathname.split("/");
return paths.pop() || paths.pop();
}
console.log(getLastPath("https://www.instagram.com/p/CBt-W4jHZjH/")); // "CBt-W4jHZjH"
console.log(getLastPath("https://www.instagram.com/p/CBt-W4jHZjH")); // "CBt-W4jHZjH"
Display the last part of URL javascript?
<script type="text/javascript">
var segment_str = window.location.pathname; // return segment1/segment2/segment3/segment4
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.write(last_segment); // alerts segment4
</script>
JsFiddle: http://jsfiddle.net/HNMV3/1/
How to get last two URL segments?
Splitting, slicing and joining is probably the easiest:
const url = 'http://mywebsite/segment1/segment2';
const lastTwo = url.split('/').slice(-2).join('/');
console.log(lastTwo);
Regex: Replace last segment of url
You could use the URL class to extract the pathname and substring
to remove the first '/'.
Then, you could put the last part of the pathname in a group and use it as a reference $1
for the replacement.
const url = new URL('https://www.test.com/one/two/three/mypost/').pathname.substring(1)
console.log(url.replace(/\/([^/]*)\/$/, '?id=$1'))
Javascript to grab last part of the document.URL?
You could simply use .split() on window.location.href
, and grab the last entry.
Example:
var lastPart = window.location.href.split("/").pop();
How to remove 2 last segment in url?
var url ='http://www.example.com/45/10/2016'
var parts = url.split('/')
// change segments
parts[4] = '12';
parts[5] = '2017';
var new_url = parts.join('/')
Get last segment of url without parameters in javascript?
You can do something this way:
// The first thing is to strip off the things after query string:
var url = "http://example.com/myfolder/mypage.aspx?x=1";
url = url.split("?")
url = url[0];
// Get the last path:
url = url.split("/");
page = url[url.length-1];
alert(page);
JavaScript get last URL segment
Maybe something like?
window.location.pathname.split('?')[0].split('/').filter(function (i) { return i !== ""}).slice(-1)[0]
- Split on '?' to throw out any query string parameters
- Get the first of those splits
- Split on '/'.
- For all those splits, filter away all the empty strings
- Get the last one remaining
Related Topics
How to Find the Operating System Details Using JavaScript
How to Handle Newlines in Json
Regex to Extract All Matches from String Using Regexp.Exec
How to Show a Running Progress Bar While Page Is Loading
Ellipsis in the Middle of a Text (MAC Style)
Jspdf Can't Get Any Styling to Work
Am I Using Too Much Jquery? When am I Crossing the Line
Force Browser to Refresh CSS, JavaScript, etc
Load Less.Js Rules Dynamically
Prevent Address-Bar Hiding in Mobile Browsers
Modify a CSS Rule Object with JavaScript
Get Computed Font-Family in JavaScript
How to Run Background Tasks in React Native
Why Can't I Access a Property of an Integer with a Single Dot
How to Round to 1 Decimal Place in JavaScript
Sort Array Elements (String with Numbers), Natural Sort
How to Check Whether a Radio Button Is Selected With JavaScript
Event Listener on a CSS Pseudo-Element, Such as ::After and ::Before