3

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!

1 Answer 1

9
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);
Sign up to request clarification or add additional context in comments.

4 Comments

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"].
Or hex numbers :P but who's counting.
@Vlad: yep, I kept that in mind but usually IDs are positive so I decided to not overcomplicate
@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. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.