Hi all,
Just a small regex challenge Iām wondering how to do nicely.
How do I get the page ID from a url that looks like this?
www.website.com/guide-me/123/results
Where 123
is the ID I want to return in a variable (ie) pageId
Thanks is advance
Assuming the url structure is always the same, you could just not use a Regex at all:
const getId = (str) => str.split('/')[2];
const pageId = getId(www.website.com/guide-me/123/results)
console.log(pageId); // 123
With a regex you have a few choices:
// get just numbers in the url, assuming the url structure is always the same
const getId = (str) => str.match(/(\d+)/)[1]
// get the same part of the url, just like the non-regex example
const getId = (str) => str.match(/www\.website\.com\/guide-me\/(\d+)\/results/)[1]
PS. Might have to double check my code and regex, did them off the top of my head with minimal testing ;D
1 Like
Thanks so much, I think the getId
function works the simplest