Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

267
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

use

const url=window.location.href.split('\//')[1]??'home'
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda