[英]RegEx to remove any comments from a JS file
我尝试创建一个脚本,该脚本将删除 JS 文件中的任何//
和/**/
注释。
该脚本目前由两个依次执行的正则表达式组成。 问题是它在一种特定情况下会中断,我目前不知道如何修复它。
var input = ` // // Line comments // // aaa alert("// xxx"); alert(x); // bbb // ccc // // Block comments // /* * aaa * bbb */ /* ccc */ /**/ alert(x); /**/ alert("/* xxx */"); alert('/* yyy */'); `; // removing line comments input = input.replace(/("[^"]*\/\/.*?")|\/\/(?:.|\r?\n)*?(?:\r?\n|.*)?/g, "$1"); // removing block comments input = input.replace(/(["'][^"']*\/\*.*?\*\/[^"']*["'])|\/\*(?:.|\r?\n)*?\*\//g, "$1"); console.log(input);
上面代码段中的 output 是错误的。 导致问题的行是
alert("// xxx");
第二个正则表达式将该行中的右引号视为开引号,并从该点开始处理。 这是一个现场演示: https://regexr.com/5n27q
如何解决?
学分:
任何一个:
gulp-strip-comments
已经这样做了。gulp-strip-comments
的源代码,看看它们如何匹配从多行到内联到缩小等所有可能形式的注释。(源代码) 如果您尝试“转换”您的 JavaScript 文件, Gulp
是您的朋友。 (:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.