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 ;

6
  • I'm assuming this is for debugging purposes? Commented Dec 6, 2012 at 15:48
  • 2
    The term for this is "instrumentation", and this question has been asked before stackoverflow.com/questions/843546/… Commented Dec 6, 2012 at 15:49
  • @RocketHazmat: I'm building a program in C#, it makes use of the V8 engine & javascriptdotnet.codeplex.com to run some scripts. I need the script to check if it should pause. Commented Dec 6, 2012 at 15:50
  • @user1816548 Thanks for the link, I'm checking. Commented Dec 6, 2012 at 15:52
  • 1
    This is not possible to do with a regex. Use a javascript parser for that. Commented Dec 6, 2012 at 15:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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#.
Just be careful that your code doesn't include e.g. a = ";" :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.