1

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.

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94

2 Answers2

2

There is no difference if you do this I think:

"20*5".split('*').reduce(function(a,c){ 
   return  a <=0? c : a*c 
 },0);

The advantage of this approach is that it will also work with "20*5*3" without changing the code

Disclaimer: I understand you may want to use regular expressions to resolve your issue. I am just providing a side view of the problem.

Dalorzo
  • 19,834
  • 7
  • 55
  • 102
1

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

GôTô
  • 7,974
  • 3
  • 32
  • 43