Not sure why this is stumping me. I need to grab the 'page' of a site. In my dev environment there is no trailing slash but on the staging server a trailing slash gets added. So, how do I return "page-name" regardless of if there's a trailing slash?
(Vanilla or jquery)
www.website.com/page-name
www.website.com/page-name/
My long solution... is there a shorter way?
let { href } = window.location;
let lastChar = href.substr(-1);
let ref;
if (lastChar === "/") {
ref = href.slice(0, -1);
} else {
ref = href;
}
let pageName = ref.split("/").pop();
You can use location.pathname to get the path, then split by / and get the second item in the resulting array:
const result = location.pathname.split("/")[1]
Regex possibly? get the last capture group.
let { href } = window.location;
const match = href.match(/\/([\w-]+)/g);
console.log(match[match.length - 1]);
use
const url=window.location.href.split('\//')[1]??'home'