0

I have an expression such as xsin(x) it is valid only if * comes between x and sin(x) and make it as x*sin(x)

my idea is first search for x then insert * between x and another variable if there is a variable.

equation

  1. sin(x)cos(x) to sin(x)*cos(x)

  2. pow((x),(2))sin(x)to pow((x),(2))*sin(x)

  3. sin(x)cos(x)tan(x) to sin(x)*cos(x)*tan(x)

    etc

I am trying with this code..

function cal(str)
{

  //var string = "3*x+56";
  var regex = /([a-z]+)\(\(([a-z]+)\),\(([0-9]+)\)\)\(([a-z0-9\*\+]+)\)([\*\-%\/+]*)/;
  var replacement = "$1($2($4),($3))$5";
  while(str.match(regex))
    {
      str = str.replace(regex,replacement);
    }
  return str;
}
Community
  • 1
  • 1
smraj
  • 152
  • 9

2 Answers2

2
> 'sin(x)cos(x)'.replace(/(?!^)\w{3}/g, '*$&')
< "sin(x)*cos(x)"
> 'pow((x),(2))sin(x)'.replace(/(?!^)\w{3}/g, '*$&')
< "pow((x),(2))*sin(x)"
> 'sin(x)cos(x)tan(x)'.replace(/(?!^)\w{3}/g, '*$&')
< "sin(x)*cos(x)*tan(x)"

This says: replace anything that doesn't start at the beginning and has three letters with a * and everything that matched

qwertymk
  • 34,200
  • 28
  • 121
  • 184
2

This one matches right parentheses followed by a letter (e.g. )s ), and inserts a * (e.g. )*s )

It also replaces x followed by a letter with x* and that letter

It should work for x+sin(x) and xsin(x)

function addStars(str) {
    return str.replace(/(\))([A-Za-z])/g,function(str, gr1, gr2) { return gr1 + "*" + gr2 }).replace(/x([A-Za-wy-z])/g,function(str, gr1) { return "x*" + gr1 })
}

document.write(addStars("x+sin(x)tan(x)ln(x)+xsin(x)"))

Help from:
JavaScript - string regex backreferences
qwertymk's answer

Community
  • 1
  • 1
Josiah Krutz
  • 957
  • 6
  • 16