1

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:

DataList[-1].MemberId
DataList[-2].MemberId

And it does, however it also matches the following:

DataList[-1].FirstName
DataList[-2].FirstName

which I don't want.

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

Thanks,

Cullen

1
  • 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. Commented Oct 26, 2009 at 17:26

3 Answers 3

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

2

The or is saying:

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

This regex matches correctly:

DataList\[-?\d{1,3}\]\.MemberId

Comments

1

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]

Comments

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.