简体   繁体   English

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

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

So if I had the following string: 因此,如果我有以下字符串:

'(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'

I could look through the string and push any numbers in the string to an array, which would look like this: 我可以查看字符串,并将字符串中的任何数字推入数组,如下所示:

[01,04,07,10,14]

Use a regular expression: 使用正则表达式:

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

This will result in ["01", "04", "07", "10", "14"] (array of strings). 这将导致["01", "04", "07", "10", "14"] (字符串数组)。 If the type of the elements matters to you you can follow up with .map(Number) to convert to numbers: 如果元素的类型对您很重要,则可以使用.map(Number)转换为数字:

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

which will result in [1, 4, 7, 10, 14] . 这将导致[1, 4, 7, 10, 14]

Note that map is not available in IE earlier than version 9, so depending on your compat requirements you might need a polyfill. 请注意,在版本9之前的IE中, map不可用,因此根据您的兼容性要求,可能需要使用polyfill。 There's a ready-made one on MDN. 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);
});

For browsers that does not support Array.prototype.map , use this code: 对于不支持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