Kirk Ross
Kirk Ross

Reputation: 7153

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

Upvotes: 0

Views: 52

Answers (3)

Sparrow
Sparrow

Reputation: 390

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);

Upvotes: 0

DecPK
DecPK

Reputation: 25398

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);

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370669

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

Upvotes: 2

Related Questions