Arya Mehta
Arya Mehta

Reputation: 151

Regex to match a 2-digit number in Jquery

multiplier_h = $item.attr('class').match(/item-h(\d)/)

it matches item-h3 class correctly but if it is item-h12 then it just matches item-h1

so what should be change in above code to match 2nd digit also.

thanks.

Upvotes: 1

Views: 1714

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173522

A few things:

  1. Because you can have more than one class I would recommend to match the neighbouring spaces and pad the subject,
  2. To make it more generic, you can match as many digits as it can find, so that it will match item-h100 as well.

So:

var str = ' ' + $item.attr('class') + ' '; // pad with spaces

multiplier_h = str.match(/\sitem-h(\d+)\s/);

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 148980

A pattern like this will match a one or two digit number

/item-w(\d\d?)/

And a pattern like this will match a number with one or more digits:

/item-w(\d+)/

But in general, you can use {n,m} to match any number of digits from n to m. For example, to match anywhere from 1 to 5 digits:

/item-w(\d{1,5})/

Upvotes: 1

Related Questions