ProfK
ProfK

Reputation: 51114

JavaScript RegEx Elements Match

I'm trying to match elements with a name that is 'container1$container2$chkChecked', using a regex of '.+\$chkChecked', but I'm not getting the matches I expect when the element name is as described. What am I doing wrong?

Upvotes: 1

Views: 304

Answers (5)

moonshadow
moonshadow

Reputation: 89185

There's two levels of escaping: one when your code is first parsed (e.g. in case you want to include a ' inside the string), and the second in the regexp engine. So you need two \s before the $ to make the regexp engine not treat it as a special character.

Upvotes: 2

ProfK
ProfK

Reputation: 51114

Steven Noble:

which won't work because js takes advantage of the \ in its string interpretation as an escape so it never makes it into the regex interpreter

I intended to use \ as an escape because I'm really looking for a $ in the element name.

Upvotes: 0

Steven Noble
Steven Noble

Reputation: 10425

my guess, by your use of quotes, is you did something like

re = new RegExp('.+\$chkChecked');

which won't work because js takes advantage of the \ in its string interpretation as an escape so it never makes it into the regex interpreter

instead you want

re = new RegExp('.+\\$chkChecked');

Upvotes: 3

brien
brien

Reputation: 4440

It looks like it should work.

There's a good Javascript Regex Tester that also says it matches.

Upvotes: 0

Kent Fredric
Kent Fredric

Reputation: 57414

try

string.match( /[$]chkChecked$/ ) 

alternatively, you could try

string.match( /[^a-zA-Z0-9]chkChecked/ ) 

( Also, make sure your using // around your regex, otherwise you might be matching using string literals. Not obvious tho without a larger code snippet )

Upvotes: 3

Related Questions