查找字符串中的数字并将它们加在一起 [英] Finding numbers in a string and adding them together

查看:81
本文介绍了查找字符串中的数字并将它们加在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道jQuery是否有可能将数字加到字符串中...

I was wondering if it were possible with jQuery to add together numbers in a string...

只能将字符串添加到其自身,如下面的示例所示.如果出现一个或多个字符串,则应将其合并.

The strings can only be added to themselves as shown in the examples below. If one or more of the string appears, it should be combined.

所有可能的字符串:单击此处

带有可能的字符串的示例:

Example with possible strings:

+0.53 attack damage
+0.53 attack damage
= 1.06 attack damage

+8.75 mana
+8.75 mana
= 17.5 mana

其中的每一个最多可以合并 9次.

Each of these can be combined up to 9 times.

推荐答案

使用此正则表达式:

/((-|\+)?([0-9]+|)(\.?[0-9]+))/g

您可以使用 Array.prototype.reduce 像这样将您的数字加起来

You can use Array.prototype.reduce like this to sum your numbers up

var str = 'Hello +0.50 World Hello 1 World Hello -10 World',
    re = /((-|\+)?([0-9]+|)(\.?[0-9]+))/g,
    sum;

sum = (str.match(re) || []).reduce(function (prev, current) {
   if (Object.prototype.toString.call(prev) !== '[object Number]') {
       prev = parseFloat(prev, 10);
   }
   return prev + parseFloat(current, 10);
}, 0);

// sum should be equal to -8.5 here

请注意,str.match(re)可能返回null,因此我们只需确保在数组上调用reduce.

Note that str.match(re) may return null, so we just make sure we call reduce on an array.

这篇关于查找字符串中的数字并将它们加在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆