最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - How to extract array of numbers from string in javascript - Stack Overflow

programmeradmin3浏览0评论

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 mas (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!

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 mas (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 asked Apr 19, 2013 at 2:53 RaevenneRaevenne 572 silver badges6 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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);
发布评论

评论列表(0)

  1. 暂无评论