开发者

javascript iterate over string

开发者 https://www.devze.com 2023-03-06 13:45 出处:网络
I have a string like this: Cars: 5 Fruits: 2 Cars: 1 Carrier: 20 Cars: 20 Hey开发者_如何学Python: 2\"

I have a string like this:

Cars: 5
Fruits: 2
Cars: 1
Carrier: 20
Cars: 20
Hey开发者_如何学Python: 2"

How do I get all the Cars values into an Array?

I want to end up with this:

[5, 1, 20]

Thanks.


I'd probably go with something like this, based on John Resig's "Search and don't replace" method.:

var arr = [];
str.replace(/Cars:\s(\d+)/g, function ($0, num) {
    arr.push(+num);
});

Working demo: http://jsfiddle.net/wCLTe/1

0

精彩评论

暂无评论...
验证码 换一张
取 消