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
Advertisement
Answer
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 whitespacesconsole.log(– a literalconsole.log(text.*– any zero or more chars other than line break chars as many as possible)– a)char;?– an optional;char.