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

212
Visualizações
Better way to extract a string in Javascript

I have a string which is

xyz.com/test/classified/electronics/home-audio-turntables/amplifiers/new/.

I want to extract following value from above string i.e., /classified/electronics/home-audio-turntables/amplifiers/

I'm able to achieve this with the code below but is there a better way than this? Appreciate suggestions

window.location.href.split('test')[1].split('/new')[0]
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

A regular expression can match what comes between.

const str = 'xyz.com/test/classified/electronics/home-audio-turntables/amplifiers/new/';

const result = str.match(/test(\/.*?\/)new/)[1];
console.log(result);

Or with lookbehind

const str = 'xyz.com/test/classified/electronics/home-audio-turntables/amplifiers/new/';

const result = str.match(/(?<=test)\/.*?\/(?=new)/)[0];
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

I think what you are looking for is window.location.pathname

In case of testing:

window.location.pathname.replace(/^(\/test)?/, '')
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