【问题标题】:get all numbers in a string and push to an array (javascript)获取字符串中的所有数字并推送到数组(javascript)
【发布时间】:2014-03-03 07:43:59
【问题描述】:

如果我有以下字符串:

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

【问题讨论】:

标签: javascript arrays string replace numbers


【解决方案1】:

使用正则表达式:

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]

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

【讨论】:

  • 我认为他想要输出数组中的数字。
  • @DaniloValente:几乎在所有情况下都不应该有所作为。但我相应地扩展了答案。
【解决方案2】:
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);
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-17
  • 1970-01-01
  • 1970-01-01
  • 2021-02-19
相关资源
最近更新 更多