获取字符串中的所有数字并推送到数组(javascript) [英] get all numbers in a string and push to an array (javascript)

查看:302
本文介绍了获取字符串中的所有数字并推送到数组(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]

推荐答案

使用正则表达式:

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

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

This will result in ["01", "04", "07", "10", "14"] (array of strings). If the type of the elements matters to you you can follow up with .map(Number) to convert to numbers:

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

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

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

Note that map is not available in IE earlier than version 9, so depending on your compat requirements you might need a polyfill. There's a ready-made one on MDN.

这篇关于获取字符串中的所有数字并推送到数组(javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆