Multiply regex and replace them in string

I am trying to multiply the amounts in a recipe using regex replacement.

Here is a sample 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 to the place. I am trying to find a way to multiply a matching number, and then replace the old 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 result that I get:

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

Can someone point me in the right direction how to convert "$ &"? for the float so that I can multiply it?

Many thanks!

+4
source share
1 answer

You need to parse the 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 propagate strings in javascript!

 "" * 2 // NaN 
+6
source

Source: https://habr.com/ru/post/1396422/


All Articles