Regex: How to get page ID from url

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?

Where 123 is the ID I want to return in a variable (ie) pageId

Thanks is advance :slight_smile:

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(
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 :slight_smile: