Home > Blockchain >  How to replace a full console logs with preceding whitespaces and possible new line from string with
How to replace a full console logs with preceding whitespaces and possible new line from string with

Time:07-02

I need to replace a console.log('') construction in a string using regex. Before the console log there can be random number of whitespaces and one or zero new line characters '\n'. I want to delete it together with the console log. Here is my code:

const consoleRegex = new RegExp(/\\n?\s console\.log\(.*\);?/);
let v = "<script>\n  console.log('test');\n</script>"

v = v.replace(consoleRegex, '');

The desired result is <script>\n</script>. When I test the regex in the tester it works however it does not get replaced.

Thanks

CodePudding user response:

You can use

let v = "<script>\n  console.log('test');\n</script>";
console.log(v.replace(/\s console\.log\(.*\);?/, ''));

See the online demo

Output:

"<script>\n</script>"

Details:

  • \s - one or more whitespaces
  • console\.log\( - a literal console.log( text
  • .* - any zero or more chars other than line break chars as many as possible
  • \) - a ) char
  • ;? - an optional ; char.
  • Related