[英]Replace line comment(//) to block comment(/*) regex JS
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.我想获得一个正则表达式来替换所有行注释以阻止注释,但我只想返回合法的 js 注释而不是
//
这是字符串的一部分,因为我必须检测//
是否在引号中而不是替换它.
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*/
.将注释与
/(?:(?=["'][^"']*$)|(?=^[^"']*\/\/.*$))(.*?)\/\/(.*)/gm
匹配/(?:(?=["'][^"']*$)|(?=^[^"']*\/\/.*$))(.*?)\/\/(.*)/gm
并替换为$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.