Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for two digit number

If i do:

var pageNum= 2;

nextLink = http://mydomain.com/?paged=1 

nextLink = nextLink.replace(/\/?paged=[0-9]?/, 'paged='+ pageNum);

I get

nextLink = 'http://mydomain.com/?paged=2';

But if I go:

var pageNum= 12;

nextLink = http://mydomain.com/?paged=10 

nextLink = nextLink.replace(/\/?paged=[0-9]?/, 'paged='+ pageNum);

I get

netLink = 'http://mydomain.com/?paged=120'; 

When I want:

nextLink = 'http://mydomain.com/?paged=12';

So, how can I use a two digit number (11, 12, 13, 14 etc) and replace it with the pageNum variable (which can be both a one and two digit number).

Thank's!

like image 981
user3345564 Avatar asked Jun 24 '14 14:06

user3345564


1 Answers

There are multiple ways to write a regex checking for 2 digits, each with their own goal:

[0-9]+

means 1 or more digits;

\d\d

means exactly 2 digits and also works for digits which are in another base (like Hex);

[1-9][0-9]

means any number between 10 and 99.

[1-9][0-9]?

means any number between 1 and 99.

The best option depends on if you need support for triple digit numbers as well, and if you need to support a page 0. if you need triple numbers, you can go with Avinash' solution. if you only want those with double digits, go with [1-9][0-9]. if you want both single and double digits, go with my 4th solution.

like image 135
Nzall Avatar answered Sep 30 '22 20:09

Nzall