Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply regex matches and replace them in string

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!

like image 476
Riccardo Bartoli Avatar asked Feb 14 '12 15:02

Riccardo Bartoli


People also ask

How do I replace a word in a string in regex?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.

Does string replace take regex?

The Regex. Replace(String, MatchEvaluator, Int32, Int32) method is useful for replacing a regular expression match if any of the following conditions is true: The replacement string cannot readily be specified by a regular expression replacement pattern.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.


1 Answers

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
like image 145
sinsedrix Avatar answered Sep 27 '22 17:09

sinsedrix