0

I'm awful with RegEx to begin with. Anyway I tried my best and think I got pretty far, but I'm not exactly there yet...

What I have: A javascript source file that I need to process in Node.js. Can look like that:

var str = "require(test < 123)\n\nrequire(test2 !== test)\n\nfunction(dontReplaceThisParam) {\n    console.log(dontReplaceThisParam)\n}";

What I came up with:

console.log(str.replace(/\(\s*([^)].+?)\s*\)/g, 'Debug$&, \'error_1\''))

Theres a few problems:

  1. I want that the string error gets inside the paranthesis so it acts as a second parameter.
  2. All function calls, or I think even everything with paranthesis will be replaced. But only function calls to "require(xxx)" should be touched.
  3. Also, the error codes should somehow increment if possible...

So a string like "require(test == 123)" should convert to "requireDebug(test == 123, 'error_N')" but only calls to "require"...

What currently gets outputted by my code:

requireDebug(test < 123), 'error_1'

requireDebug(test2 !== test), 'error_1'

functionDebug(dontReplaceThisParam), 'error_1' {
    console.logDebug(dontReplaceThisParam), 'error_1'
}

What I need:

requireDebug(test < 123, 'error_1')

requireDebug(test2 !== test, 'error_2')

function(dontReplaceThisParam) {
    console.log(dontReplaceThisParam)
}

I know I could just do things like that manually but we're talking here about a few hundred source files. I also know that doing such things is not a very good way, but the debugger inside the require function is not working so I need to make my own debug function with an error code to locate the error. Its pretty much all I can do at the moment...

Any help is greatly appreciated!

1 Answer 1

1

Start the regex with require, and since you need an incrementing counter, pass a function as the second arg to replace, so that you can increment and insert the counter for each match.

var str = "require(test < 123)\n\nrequire(test2 !== test)\n\nfunction(dontReplaceThisParam) {\n    console.log(dontReplaceThisParam)\n}";
var counter = 0;

console.log(str.replace(/require\(\s*([^)].+?)\s*\)/g, (s, g2) => 
  `requireDebug(${g2}, \'error_${++counter}\')`
));

Other than that, your code was unaltered.

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

2 Comments

Holy cow! You make this look so easy * ashamed * Thank you very much!
You're welcome, but it was easy since you wrote the majority of the regex. I just added a word. :)

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.