I want to get a regex to replace all line comments to block comments, but I want to return only legal js comments and not // that is part of a string for that I have to detect if // is in quotes and not replace it.
Now I got something like this /"(.*?\/\/.*?)"/, but it replaces the opposite - all // in quotes and not the ones without.
// Change heading:
should match
document.getElementById("myH").innerHTML = "My First //Page";
shouldn't match
document.getElementById("myP").innerHTML = "My first paragraph."; // Change paragraph:;
should match
console.log("some important info //shouldn't replace"); // this is important info
In this case, valid comment should match, but comment inside quotation marks shouldn't.
Match the comments with /(?:(?=["'][^"']*$)|(?=^[^"']*\/\/.*$))(.*?)\/\/(.*)/gm and replace with $1/*$2*/.
let code = `// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph."; // Change paragraph:
console.log("some important info //shouldn't replace"); // this is important info
console.log('some important info //should not replace'); // this is important info`;
code = code.replace(/(?:(?=["'][^"']*$)|(?=^[^"']*\/\/.*$))(.*?)\/\/(.*)/gm, "$1/*$2*/");
console.log(code);