Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

266
Views
Javascript - grab page name from url whether trailing slash or not

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();
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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]
about 4 years ago · Juan Pablo Isaza Report

0

Regex possibly? get the last capture group.

let { href } = window.location;
const match = href.match(/\/([\w-]+)/g);
console.log(match[match.length - 1]);
about 4 years ago · Juan Pablo Isaza Report

0

use

const url=window.location.href.split('\//')[1]??'home'
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!