I’m a bit rusty on my regexp and Javascript. I have the following string var:
var subject = "/admin.php?page=settings&tabs_added[114787535263592]=1&tabs_added[217770811582323]=1&tabs_added[198738186831542]=1"
I want to extract 114787535263592, 217770811582323 and 198738186831542.
I’ve tried to use non-capturing parenthesis (?:) :
var regexp = /(?:tabs_added[\[])(\d)+(?:[\]])/;
var pageid = regexp.exec(subject);
But the result I get (["tabs_added[114787535263592]", "2"]) is not what I expected — what am I doing wrong? Here’s a jsFiddle: http://jsfiddle.net/KgpAw/
You were very close. You need to capture the
+as well. Otherwise you only capture one decimal digit:You should also make your regex global to find all matches:
Then you should loop through the results, you also don’t need to have non-capturing groups because you’re not using a quantifier on them (
?,+, or*), nor do you need to put your[and]inside a character class:JSFiddle Example
Note: It’s better to use
console.logfor debugging purposes thandocument.writeas long as you have a console available. (Chrome, Opera, IE9, and Firefox have consoles built in, and I think Safari does too, so you should have one available.)console.logprovides much more valuable information when logging objects and arrays.