Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Using javascript, I need to extract the numbers from this string:

[stuff ids="7,80"]

and the string can have anywhere from one to five sets of numbers, separated by commas (with each set having 1 or more digits) that need to be extracted into an array.

I've tried:

var input = '[stuff ids="7,80"]';
var matches = input.match(/ids="(\d*),(\d*)"/);

This will give me an array with 7 and 80 in it (I think), but how do I take this further so that it will return all of the numbers if there are more than two (or less than two)?

Further, is this even the best way to go about this?

Thanks for the help!

share|improve this question

1 Answer

up vote 5 down vote accepted
var numbers = '[stuff ids="7,80"]'.match(/\d+/g);

\d+ matches any consecutive digits (which is number) and g modifier tells to match all

PS: in case if you need to match negative numbers:

var numbers = '[stuff ids="-7,80"]'.match(/-?\d+/g);
share|improve this answer
This is awesome! Just a nitpick, it won't pick up the negative sign, i.e, for '[stuff ids="7,-80"]' it'll still return ["7","80"]. – Vlad Apr 19 at 3:02
Or hex numbers :P but who's counting. – KingKongFrog Apr 19 at 3:04
@Vlad: yep, I kept that in mind but usually IDs are positive so I decided to not overcomplicate – zerkms Apr 19 at 3:04
@zerkms Thank you!! I was obviously making this terribly complicated on my own. I also appreciate the explanation of the regex. Wish I'd asked sooner. :-) – Raevenne Apr 19 at 3:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.