2

I would like to process/parse and alter some Javascript code, preferably in a regular expression if that's possible (open to suggestions). The purpose would be to insert a new code snippet after each statement in the JS.

For example:

The original Javascript:

while(true){

    Utils.log("hello world");
    Utils.sleep(1000);

}

Code snippet that I would like to insert:

checkPause();

So the new code would look like this:

while(true){

    checkPause();
    Utils.log("hello world");
    checkPause();
    Utils.sleep(1000);
    checkPause();

}
checkPause();

The example above is quite simple, but the real JS code could be more complex and could even be minified. The code could also miss out some semicolons ;

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Drahcir
  • 11,772
  • 24
  • 86
  • 128

1 Answers1

1

A very dirty way to do this would be to insert your snippet after every opening brace, closing brace, and semicolon. Like this:

 code.replace(/\;/g, '; checkPause(); ').replace(/\{/g, '{ checkPause(); ').replace(/\}/g, '} checkPause(); ')

A proper way would be to use a parser.

teh_senaus
  • 1,394
  • 16
  • 25
  • Thanks for your answer, I need to test more for my purpose but it seems to work. I have narrowed it down to `Regex.Replace(code, @"\;|\{|\}|\n", @"$0 checkPause();")` in C#. – Drahcir Dec 06 '12 at 17:08
  • Just be careful that your code doesn't include e.g. a = ";" :) – tjltjl Dec 06 '12 at 17:43