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:
var s = "https://example.com/my-list/page/35/?a=45&b=56"; // First way uses capture groups based on what comes before the page number: "/page/" s.match(//page/(d*)/)[1]; // "35"
The second way:
// The second involves using capture grouping based on the search param that appears to follow. // However, this way might not be ideal as you may extend the URI and make a major change that would then require an edit to this. Of course, that could happen with the previous as well. s.match(/(d*)(?=/?)/)[0] // "35"
You can also split
the string, and then use regex to grab just the beginning of the string:
s.split("/page/")[1].match(/^d*/); // "35"
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.
s.split("/")[5] // "35"
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:
s.substr(s.indexOf("page/")+5, 2) // "35" // +5 due to length of phrase i use
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.
s.substr(s.indexOf("page/")+5).match(/^d*/)[0] // 35