Skip to content
Advertisement

Javascript regex get only page number from URL

i have URL like https://example.com/my-list/page/35/?a=45&b=56

I want to get page number using regex that is after /page/ in url, the result i want is 35

Advertisement

Answer

There’s 2 easy ways you could do it using RegEx:

The first way:

JavaScript

The second way:

JavaScript

You can also split the string, and then use regex to grab just the beginning of the string:

JavaScript

You could also simply split the whole string based on the most common element: “/”. If your URI pattern is always the same, then this is probably one of the most simply and easy to read solutions. However, if the URI pattern changes to have more fields, then you may have to adjust the index number.

JavaScript

You could also use substr based on the index of “page”. The problem with this is the page number might be 1 digit, 2 digits, or more:

JavaScript

You could use the substr and index grab the string you want, having the page number at the very start of the string. Then use regex to pull the number and have it rest at 0 index. This might be more practical in case, for whatever reason, there is no page number. For instance, the user ends up at the “page” index base.

JavaScript
Advertisement