1

Im trying to delete all console.() from string or text and this code doesnt work, why?

var str = "console.log('test')";
var pattern = /console\..*\(.*\);/gm;
console.log(str.replace(pattern, ""));

http://plnkr.co/edit/gzFPopi1qdd6PYZz2urM?p=preview

1 Answer 1

3

It doesn't work because in your test string there is no ; however regexp expects one. Just make it optional with ?:

var pattern = /console\..*?\(.*?\);?/gm;

Also make sure the match is not greedy with .*?.

Check the test demo below.

var str = "some string console.log('test'); and console.log(123) \
console.log('123', 12, 'asd'); \
test";

alert( str.replace(/console\..*?\(.*?\);?/gm, '') );

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

Comments

Your Answer

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