Take the 2-minute tour ×

I have a javascript function that looks element id with certain patterns. So I have the following script:

if (f.elements[i].id.match(/DataList\[-\d{3}|\d{3}\]\.MemberId/)) {
  //do something

It should match elements with ids such as these:


And it does, however it also matches the following:


which I don't want.

Could any guru take a look at the regular expression above and point out what is going wrong?



share|improve this question
For the regex you posted to match the element names you listed, you'd need to change the \d{3} to \d{1,3}. See @Macarse's answer for a good explanation of what's going on. –  Brendan Berg Oct 26 '09 at 17:26
add comment

3 Answers

up vote 2 down vote accepted

Try to anchor your regex at the beginning with a ^ and at the end with a $, group your digit match and allow 1-3 digits instead of just 3.

if (f.elements[i].id.match(/^DataList\[(-\d{1,3}|\d{1,3})\]\.MemberId$/)) {
  //do something

The way you had it, it was matching anything containing "DataList[-123" or containing "123].MemberId".

A simpler overall regex that accomplishes the same thing is:

if (f.elements[i].id.match(/^DataList\[-?\d{1,3}\]\.MemberId$/)) {
  //do something
share|improve this answer
thanks Asaph. I'm using the first solution. –  Cullen Tsering Oct 26 '09 at 17:35
add comment

The or is saying:

DataList\[-\d{3} OR \d{3}\]\.MemberId/

This regex matches correctly:

share|improve this answer
thanks Macarse, this is the source of the problem. –  Cullen Tsering Oct 26 '09 at 17:34
add comment

My suggestion

   if (f.elements[i].id.match(/DataList\[-[0-9]{1,3}\]\.MemberId/)) {

The {} determines how many #s you want to support so 1-3 would match upu to [999]

share|improve this answer
add comment

Your Answer


