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