bart2puck
bart2puck

Reputation: 2522

jquery get value in brackets using regex

This has probably been asked a million times, and i am probably way off in what i have below, but i can not find it anywhere on SO. I need to get my alert below to show the value inside the brackets.

//the element(thisId) holds the following string:   id[33]     
var thisId = $(this).attr('id');
var idNum = new RegExp("\[(.*?)\]");
alert(idNum);

I need the alert to show the value 33.

Upvotes: 0

Views: 2536

Answers (2)

Barmar
Barmar

Reputation: 780724

You need to match the string with the regular expression, not just create the regexp. This returns an array containing the full match and the matches for capture groups.

var thisId = 'id[33]';
var match = thisId.match(/\[(.*?)\]/);
alert(match[1]); // Show first capture

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use exec() to get the matches to your Regex:

var thisId = 'id[33]';
var matches = /\[(.*?)\]/g.exec(thisId);
alert(matches[1]); // you want the first group captured

Example fiddle

Upvotes: 1

Related Questions