乘以正则表达式匹配并将其替换为字符串 [英] Multiply regex matches and replace them in string

查看:45
本文介绍了乘以正则表达式匹配并将其替换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式替换来将配方中的数量相乘.

I'm trying to multiply the amounts in a recipe using regex replace.

这是示例HTML代码

<div id="ingredients">
    <ul>
        <li>2 bananas, sliced</li>
        <li>1 cup frozen strawberries</li>
        <li>8 oz. low fat vanilla yogurt</li>
    </ul>
</div>

我到了这里.我正在尝试找到一种方法来将匹配的数字相乘,然后用相乘后的数字替换旧的数字:

I got as far as here. I'm trying to find a way to multiply the matched number and then replace the old one with the multiplied one:

var str   = document.getElementById('ingredients').innerHTML;
var regex = /[0-9]+(?:\.[0-9]*)?/g;
str = str.replace(regex, "$&" * 2);
console.log(str)​

但这是我得到的输出:

<ul>
    <li>NaN bananas, sliced</li>
    <li>NaN cup frozen strawberries</li>
    <li>NaN oz. low fat vanilla yogurt</li>
</ul>

任何人都可以向我指出如何转换"$&"的正确方向.到浮点数,以便我可以乘以它?

Can anyone please point me to the right direction on how to convert "$&" to a float so I can multiply it?

非常感谢!

推荐答案

您必须先将字符串解析为数字,然后才能将其相乘:

You have to parse string as a number before you can multiply it:

str = str.replace(/[0-9]+(?:\.[0-9]*)?/g, function(m) { return 2*parseFloat(m)+''; });

您不能在javascript中将字符串相乘!

You cannot multiply strings in javascript !

"" * 2 // NaN

这篇关于乘以正则表达式匹配并将其替换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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