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

时光毁灭记忆、已成空白 提交于 2019-12-02 15:47:19

问题


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]

回答1:


Use a regular expression:

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

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);

which will result in [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. There's a ready-made one on MDN.




回答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);
});

For browsers that does not support Array.prototype.map, use this code:

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);
}


来源:https://stackoverflow.com/questions/21601614/get-all-numbers-in-a-string-and-push-to-an-array-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!