George George - 5 months ago 44
Javascript Question

jQuery extract page number in URL

I need to get the last occurrence of the page number in the URL using the either a regex or string manipulation.

www.somedomain.com/about-us/meet-the-team/4/

www.somedomain.com/about-us/meet-the-team/7/section/4/

www.somedomain.com/about-us/meet-the-team/4/?val1=somevalue&val2=somevalue

I have tried

.replace(/\/\d\//)

Answer

There might be a better way but here is one:

var str = 'www.somedomain.com/about-us/meet-the-team/4/?val1=somevalue&val2=somevalue';
var digit = str.match(/\/(\d+)(?!\/\d)/);

In this case, to get the actual number use digit[1], the content of the capture group will be stored as the second value in the array you get from .match()

Summary of the regex:

  • \/(\d+) Matches a digit (which occurs 1 or more times) after a / and save the digit an a capture group
  • (?!\/\d) do a negative lookahead that matches a digit following a /

Example

Description of Regex