繁体   English   中英

获取字符串中的所有数字并推送到数组(javascript)

[英]get all numbers in a string and push to an array (javascript)

因此,如果我有以下字符串:

'(01) Kyle Hall - Osc (04) Cygnus - Artereole (07) Forgemasters - Metalic (10) The Todd Terry Project - Back to the Beat (14) Broken Glass - Style of the Street'

我可以查看字符串,并将字符串中的任何数字推入数组,如下所示:

[01,04,07,10,14]

使用正则表达式:

var numbers = str.match(/\d+/g);

这将导致["01", "04", "07", "10", "14"] (字符串数组)。 如果元素的类型对您很重要,则可以使用.map(Number)转换为数字:

var reallyNumbers = str.match(/\d+/g).map(Number);

这将导致[1, 4, 7, 10, 14]

请注意,在版本9之前的IE中, map不可用,因此根据您的兼容性要求,可能需要使用polyfill。 MDN上有一个现成的。

var str = '(01) Kyle Hall - Osc (04) Cygnus - Artereole (07) Forgemasters - Metalic (10) The Todd Terry Project - Back to the Beat (14) Broken Glass - Style of the Street';
var nums = str.match(/\d+/g);
nums.map(function (num) {
    return parseInt(num, 10);
});

对于不支持Array.prototype.map浏览器,请使用以下代码:

var str = '(01) Kyle Hall - Osc (04) Cygnus - Artereole (07) Forgemasters - Metalic (10) The Todd Terry Project - Back to the Beat (14) Broken Glass - Style of the Street';
var nums = str.match(/\d+/g);
for (var i = 0; i < str.length; i++) {
    str[i] = parseInt(str[i], 10);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM