Search code examples
javascriptregexreplaceparsefloat

How to replace expression in a string with its value?


Sorry if the question is worded badly, but what I'm trying to ask is, How would you replace a substring of a string in JS with the product of two of the captured groups? To see what I mean, look at the following line. How would I perform a task like the following:

expression.replace(regexp,parseFloat("$1")*parseFloat("$3"));

when "regexp" is /(\d+(\.\d+)?)\*(\d+(\.\d+)?)/ and "expression" is "20*5"?

It doesn't work, and I'm not really sure why. expression.replace(regexp,"$1_$3") prints out 20_5, so why would putting "$1" and "$3" in parseFloat() change their values from the values of the first and third groups to the strings "$1" and "$3"?

If you're wondering, this is for the website GraphWidget as a STEM project for PLTW class.

Thanks.


Solution

  • You can try this:

    "20*5".replace(
                     /(\d+(\.\d+)?)\*(\d+(\.\d+)?)/,
                     function (match, group1, group2, group3) { 
                       return parseFloat(group1)*parseFloat(group3) 
                     }
                  );
    

    See this doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace