user1513171
user1513171

Reputation: 1974

JavaScript Regular Expression Can't get a matched group

I'm trying to use JavaScript regular expression with the exec function and hoping to get matches for a group. I just can't figure out why I'm getting no matches.

Here is my code:

var elementClass="validate[required]"
var myRegexp = /validate\\[(*)\\]/g;
var match = myRegexp.exec(elementClass);

match is null every time. I can't figure out why. It should be getting "required".

Thanks for the help!

Upvotes: 1

Views: 122

Answers (2)

VladL
VladL

Reputation: 13033

1) You have to many slashes

var myRegexp = /validate\[(.*?)\]/g;

2) If you want to match the part in square brackets only, you should use groups

var result = match[1];

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

Use this instead:

var myRegexp = /validate\[(.*)\]/;

First of all you only need one backslash to escape - otherwise you're searching for a literal backslash followed by the special meaning of what you were trying to escape.

Second, * just means "zero or more of the last thing", which in this case makes no sense because there is nothing there. . means "anything" (well, almost) so .* means "any number of anythings".

Finally, the g flag is unnecessary here, especially if you're trying to capture a part of the result.

Upvotes: 3

Related Questions