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

269
Views
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 answers
Answer question

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 Report

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 Report

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 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!