Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

275
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

0

use

const url=window.location.href.split('\//')[1]??'home'
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda