Multiply regex matches and replace them in string

可紊 提交于 2021-02-04 18:41:30

问题


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

Here is the example HTML code

<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)​

But this is the output I get:

<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?

Many thanks!


回答1:


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)+''; });

You cannot multiply strings in javascript !

"" * 2 // NaN


来源:https://stackoverflow.com/questions/9279517/multiply-regex-matches-and-replace-them-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!