我有这个功能,总结了正则表达式的结果:
'use strict';
function sum(string) {
var match, result, pattern;
pattern = /[\d,\.]+/g
match = string.match(pattern);
if (!match.length) {
return 'Didn\'t find any trace.';
}
result = match.reduce(function(prev, curr) {
curr = curr.replace(/\./g, '').replace(',', '.');
return prev + (+curr);
}, 0);
if (!isNaN(result)) {
return result;
} else {
return 'The sum fails.';
}
}
console.log(sum('156,02 10')); // expected: 166.02 = works
console.log(sum('10.10 10.10')); // expected: 20.20 = doesn't work, result = 2020
console.log(sum('01.10 2,30')); // expected: 3.40 = doesn't work, result = 112.3

只有当我的格式为152,02时才能正常工作。我希望它接受所有格式。可能吗?没有任何lib可以提供帮助吗?
感谢。
答案 0 :(得分:0)
尝试在.replace(/\./g, '')
之前删除+
,包括prev
运算符,将prev
字符串转换为Number
'use strict';
function sum(string) {
var match, result, pattern;
pattern = /(\d+\.\d+)|(\d+,\d+)|(\d+)/g;
match = string.match(pattern);
if (!match.length) {
return 'Didn\'t find any trace.';
}
result = match.reduce(function(prev, curr) {
curr = curr.replace(',', '.');
return +prev + (+curr);
}, 0);
if (!isNaN(result)) {
return result;
} else {
return 'The sum fails.';
}
}
console.log(sum('156,02 10')); // expected: 166.02 = works
console.log(sum('10.10 10.10')); // expected: 20.20 = doesn't work, result = 2020
console.log(sum('01.10 2,30')); // expected: 3.40 = doesn't work, result = 112.3