你如何从javascript字符串中获取数组? 说我有以下内容:
var slop = "I bought 3 but 8 4.2 of them, mmmmhghrhghrghghrgh456";
你怎么能得到以下数组:
nums = [3, 8, 4.2, 456];
注意:如果可能的话,我不想使用jQuery。
答案 0 :(得分:4)
你可以这样做:
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 });
结果:[3, 8, 4.2, 456]
答案 1 :(得分:1)
基本正则表达式获取:
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);
结果:
["3", "8", "4.2", "456", ".45"]
修改强>
更新为使用非前缀0.xx小数。如果那不是你想要的,那就是旧的正则表达式来匹配它(忽略点)全数字:
var result = string.match(/(\d+\.?\d*)/g);
旧结果:
["3", "8", "4.2", "456", "45"]