0

I'm going to try my best to explain this string manipulation.

I would like to write a JavaScript function that takes a string (preferably from a message textbox but it will be initially stored in a variable for this example) and looks for every instance of the power function "Pow()". Then, takes the contents of the "base" portion of the power function "Pow(base,exponent)" and replace it with the absolute function "Abs()" with the contents inside that so the result is "Pow(Abs(base),exponent)". The base can be anything; a word, an equation, or another function. result out to another message textbox.

for example

input: return(1.0-step(snoise(vec2(5.0*pow(iGlobalTime,2.0)+pow(uv.x*7.0,1.2),pow((mod(iGlobalTime,100.0)+100.0)*uv.y*0.3+3.0,staticHeight))),staticAmount))*staticStrength;

output: return(1.0-step(snoise(vec2(5.0*pow(abs(iGlobalTime),2.0)+pow(abs(uv.x*7.0),1.2),pow(abs((mod(iGlobalTime,100.0)+100.0)*uv.y*0.3+3.0),staticHeight))),staticAmount))*staticStrength;

I'm well aware of the .match and string.replace() functions but this is a little more complex. Can anyone lead me in the right direction?

<textarea id = "output" rows="25" cols="55" ></textarea>

<script>

inputStr = "return(1.0-step(snoise(vec2(5.0*pow
            (iGlobalTime,2.0)+pow(uv.x*7.0,1.2),pow
            ((mod(iGlobalTime,100.0)+100.0)*uv.y*0.3+3.0,
            staticHeight))),staticAmount))*staticStrength;"

function baseReplacer(input)
{

}

var outputStr = baseReplacer(inputStr);
document.getElementById("output").value = outputStr;

</script>
IscA
  • 59
  • 5
  • This isn't really a job for regular expressions since you have recursive/nested parenthesis: https://stackoverflow.com/questions/546433/regular-expression-to-match-balanced-parentheses – Nick Parsons Jan 01 '20 at 04:09
  • 1
    Just a thought... One option is to replace all the `pow(` with, say, `powAbs(` and then just write a wrapper function named `powAbs()` that applies the `abs()` to the base parameter. – Trentium Jan 01 '20 at 17:24

1 Answers1

0

I will try to describe the pseudo algorithm:

For every match of the substring pow(: From the next position, you either will find nested brackets in first argument, or a simple argument, and then a comma. If you find brackets, iterate through each position adding +1 to a counter every open bracket, and -1 for every close bracket. When the counter is set to zero, next comma is sure to end the first parameter string.

Got the idea ?

Happy 2020 ;)

Niloct
  • 8,081
  • 3
  • 38
  • 50