当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Sum all kind of number resulting from regular expression

问题描述:

I'm working on a function which sum's all numbers from a text:

'use strict';

var sum = function(text, regex) {

var match;

return !!(match = text.match(regex || /\d+/g)) ?

match.reduce(function(prev, curr) {

return +prev + +curr;

})

: 0;

}

console.log(sum('1 12 40'));

console.log(sum('10 12 40'));

console.log(sum('1 12 510'));

console.log(sum('LLLLLLLL'));

console.log(sum('10 1'));

网友答案:

Use a regex which matches numbers with decimal point too

var sum = function(text, regex) {
  return (text.match(regex || /\d*(?:\.\d*)?/g) || [])
  .reduce(function(prev, curr) {
    return prev + +curr;
  }, 0);
}
document.write(sum('1.10 12.40 40.30'));
网友答案:

If sum is expecting number as string to be parameter, could use String.prototype.split() with RegExp /\s/ , Array.prototype.map() with Number as callback

"use strict";

var sum = function(text, regex) {
  var match;
  return !!(match = text.split(regex || /\s/).map(Number)) ?
    match.reduce(function(prev, curr) {
      return prev + curr;
    })
  : 0;
}

console.log(sum("1.10 12.40 40.30"));
网友答案:

Given the format of input string, you could first use String split() to split the values, then loop to sum up the values:

function sum(text) {
  var arr = text.split(" ");
  var total = 0;
  for (var i in arr) {
    if (/[\d.]+/g.test(arr[i])) {
      total += parseFloat(/[\d.]+/g.exec(arr[i]));
    }
  }
  document.write("The sum is " + total);
}
sum("1.10 12.40 40.30");
分享给朋友:
您可能感兴趣的文章:
随机阅读: