简体   繁体   English

如何从JavaScript中的字符串获取数字数组

[英]How to get an array of numbers from a string in javascript

How would you get an array of numbers from a javascript string? 您如何从JavaScript字符串中获取数字数组? Say I have the following: 说我有以下几点:

var slop = "I bought 3 but 8 4.2 of them, mmmmhghrhghrghghrgh456";

How could you get the following array: 您如何获得以下数组:

nums = [3, 8, 4.2, 456];

Note: I'd like to not have to use jQuery if possible. 注意:如果可能,我不想使用jQuery。

You can do this : 你可以这样做 :

var s = "I bought 3 but 8 4.2 of them, mmmmhghrhghrghghrgh456";
var nums = s.split(/[^\d\.]+/).map(parseFloat)
    .filter(function(v){ return v===v });

Result : [3, 8, 4.2, 456] 结果: [3, 8, 4.2, 456]

Basic regex fetching: 基本正则表达式获取:

var string = 'I bought 3 but 8 4.2 of them, mmmmhghrhghrghghrgh456 hello.45';
var result = string.match(/((?:\d+\.?\d*)|(?:\.\d+))/g);
console.log(result);

Result: 结果:

["3", "8", "4.2", "456", ".45"]

Edit 编辑

Updated to work with non-prefixed 0.xx decimals. 更新为使用非前缀的0.xx小数。 If that's not what you want, this was the old regex to match it as (ignore dot) full numeral: 如果这不是您想要的,这是旧的正则表达式,将其匹配为(忽略点)全数字:

var result = string.match(/(\d+\.?\d*)/g);

Old Result: 旧结果:

["3", "8", "4.2", "456", "45"]

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

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