Here's my current code:
var loc = window.location.pathname;
var str = loc.substring(0, loc.lastIndexOf('/'));
var subid = str.replace("/", "");
When I go to http://example.com/12345/
, then subid
equals 12345
.
But when I go to http://example.com/12345
, then subid
is blank.
How can I make this work with or without the trailing slash?
If you consider regex,
var loc = window.location.pathname;
var subid = loc.match(/^http[s]?:\/\/.*?\/([a-zA-Z-_]+).*$/)[1];
Test with different cases
var url1 = "http://google.com/abc-1";
var url2 = "http://google.com/abc-2/";
var subid1 = url1.match(/^http[s]?:\/\/.*?\/([a-zA-Z-_]+).*$/)[1];
var subid2 = url2.match(/^http[s]?:\/\/.*?\/([a-zA-Z-_]+).*$/)[1];
console.log(subid1);
console.log(subid2);
Try this one.
var loc="http://example.com/12340/";
if((loc.length-1)==loc.lastIndexOf('/'))
{
var newloc=loc.substring(0,loc.length-1);
var subid=newloc.substring((newloc.lastIndexOf('/')+1),newloc.length);
}
else
{
var subid=loc.substring((loc.lastIndexOf('/')+1),loc.length);
}
console.log("sub is "+subid);
So much overkill and code that doesn't work in older browsers in other answers. It's as simple as this:
var subid = location.pathname.match(/^\/([^\/]*)/)[1];
You can assign the result of match
to another variable and add more groupings to the regex if you need to capture other segments, too.
if you want to extract last part of string then you can use
loc.substring(loc.lastIndexOf('/')).replace('/','');
in case of last '/ first check with .endsWith('/')
method and then remove last '/' using
if(loc.endsWith('/')) {
loc.substring( -1, loc.lastIndexOf('/')).replace('/','');
}
alternative way is
loc.split('/').filter( path => !path).pop();
You can take a benefit of inbuilt function URL
(new URL('http://example.com/12345/')).pathname.replace(/\//g,'') // output 12345
(new URL('http://example.com/12345')).pathname.replace(/\//g,'') // output 12345
The one who are looking for the last segment only can use this function
var allPartsOfURL = 'http://example.com/12345/12/98/567'.split('/');
// handle potential trailing slash
var lastSegment = allPartsOfURL.pop() || allPartsOfURL.pop();
console.log(lastSegment);
For old browsers
// create an anchor tag
const url = document.createElement('a');
// set the href attribute and then use the `pathname`
url.setAttribute('href', 'http://example.com/12345/');
url.pathname.replace(/\//g,''); // output 12345
url.setAttribute('href', 'http://example.com/12345');
url.pathname.replace(/\//g,''); // output 12345
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.