1
如何從JavaScript字符串中獲取數字數組? 說我有以下幾點:如何從javascript中的字符串中獲取數字數組
var slop = "I bought 3 but 8 4.2 of them, mmmmhghrhghrghghrgh456";
你怎麼能得到下面的數組:
nums = [3, 8, 4.2, 456];
注:我想不會有可能的話使用jQuery。
如何從JavaScript字符串中獲取數字數組? 說我有以下幾點:如何從javascript中的字符串中獲取數字數組
var slop = "I bought 3 but 8 4.2 of them, mmmmhghrhghrghghrgh456";
你怎麼能得到下面的數組:
nums = [3, 8, 4.2, 456];
注:我想不會有可能的話使用jQuery。
你可以這樣做:
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]
基本的正則表達式取:
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"]
+1 - 幹得好。 – j08691 2013-03-22 19:45:29
這絕對是太棒了,謝謝。它甚至不會被''你好.45''' – James 2013-03-22 19:47:04
+1性感,非常性感。當我開始想出一個解決方案時,你用快速的忍者技能來了。 – 2013-03-22 19:47:11