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:
JavaScript
x
5
1
const consoleRegex = new RegExp(/\n?s+console.log(.*);?/);
2
let v = "<script>n console.log('test');n</script>"
3
4
v = v.replace(consoleRegex, '');
5
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
JavaScript
1
3
1
let v = "<script>n console.log('test');n</script>";
2
console.log(v.replace(/s+console.log(.*);?/, ''));
3
See the online demo
Output:
JavaScript
1
2
1
"<script>n</script>"
2
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.