candy 5.5, icecream 3.4, something valuable 1,185.5*2
我专门使用 .
和 ,
作为分隔符。
我需要从这个字符串中获取
var sum = 5.5 + 3.4 + 1185.5*2
最佳答案
我的选择是这样的:
var buildSumString = function(testString) {
rx=/(\d[\d\.\*]*)/g
return 'var sum = ' + testString.match(rx).join(' + ');
};
var testString = "candy 5.5, icecream 3.4, something valuable 1,185.5*2";
var rebuiltString = buildSumString(testString);
此处要做的唯一假设是数字字符串中不会有空格,尽管可以轻松添加空格。
关于javascript - 使用 javascript 从字符串中获取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5281709/