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

270
Vistas
JavaScript - more concise way to grab string between two characters in URL?

Is there a more concise or more standard way to grab a string between the last slash and query question mark of a URL than this?

const recordId= window.location.href.split("item/")[1].split("?")[0]

In this case I'm using item/ because my URLs are always:

mysite.com/item/recordIdIwantToGrab?foo=bar&life=42

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

A regular expression can do the trick - match a /, followed by word characters, up until a ?.

const str = 'mysite.com/item/recordIdIwantToGrab?foo=bar&life=42';
const result = str.match(/\/(\w+)\?/)[1];
console.log(result);

  • \/ - match a literal /
  • (\w+) - capturing group, match word characters
  • \ - match a literal ?
  • [1] - extract the value matched by the capturing group
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can achieve the result using lastIndexOf and indexOf

const str = `mysite.com/item/recordIdIwantToGrab?foo=bar&life=42`;
const result = str.slice(str.lastIndexOf("/") + 1, str.indexOf("?"));
console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

We can achieve with URL class in javascript.

let url = 'http://example.com/item/recordIdIwantToGrab?foo=bar&life=42';
url = new URL(url);
let result = url.pathname.split('/').at('-1');
console.log(result);

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