0

I want to catch if the url is a blog page or not. A blog page can be:

  • /blog
  • /blog/page/1
  • /blog/page/143

So, page/pageNumber is optional. How can I create a regular expression that being tested returns true if the url is a blog page?

I created the regex for urls containing /page/ string and it seems to work fine:

/\/blog\/page\/[1-9]([0-9]*)/

Example:

> /\/blog\/page\/[1-9]([0-9]*)/.test("/blog/page/1")
true
> /\/blog\/page\/[1-9]([0-9]*)/.test("/blog/page/0")
false
> /\/blog\/page\/[1-9]([0-9]*)/.test("/blog/page/30")
true

But how can I set /page/number to be optional?

I tried:

/\/blog(\/page\/[1-9]([0-9]*))?/

This returns true for incorrect urls:

> /\/blog(\/page\/[1-9]([0-9]*))?/.test("/blog/p")
true
2
  • what's wrong with /^\/blog/i if you're using test() ? Commented Jun 25, 2014 at 7:56
  • @dandavis /blog/1-my-interesting-post is not the same with /blog/page/1. Commented Jun 25, 2014 at 7:57

4 Answers 4

1

You should add an end marker ($) so that it stops checking.

> /\/blog(\/page\/[1-9]([0-9]*))?$/.test("/blog/p")
false
> /\/blog(\/page\/[1-9]([0-9]*))?$/.test("/blog/page/1")
true
> /\/blog(\/page\/[1-9]([0-9]*))?$/.test("/blog/page/0")
false
> /\/blog(\/page\/[1-9]([0-9]*))?$/.test("/blog/page/30")
true
> /\/blog(\/page\/[1-9]([0-9]*))?$/.test("/blog")
true
Sign up to request clarification or add additional context in comments.

Comments

1

You can use this regex to make /page/num optional:

/^\/blog(\/page\/\d+)?\/?$/

4 Comments

Yes it won't and that is not in the requirements either.
It will still match /blog/p and /blog/page. Since the Javascript test() method is satisfied with a partial match.
Yes true, have added anchors now to avoid that situation.
@anubhava Also, /blog/page/0 shouldn't be matched. Anyways, thank you, all!
1

You want to add markers for the start (^) and end ($) of the string. In it's current form, your check will also return true if it only matches part of the string.

/^\/blog(\/page\/[1-9]([0-9]*))?$/

Check out this fiddle.

Comments

0

You could use non capturing groups for this,

^\/blog(?:\/page(?:\/[1-9]\d*)?)?$

3 Comments

why would capturing matter when using /./.test() ?
@dandavis it won't capture anything.
@AvinashRaj This will catch /blog/page/0 that is incorrect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.