简体   繁体   English

如何仅删除以“ //”开头的JavaScript注释?

[英]How do I remove ONLY JavaScript comments that start with “// ”?

To clarify first, I already have a compression tool that successfully compresses EVERYTHING else so I don't need a long complicated preg_replace regex, just a simple preg_replace or str_replace rule will do. 首先要说明的是,我已经有一个压缩工具可以成功地压缩其他所有东西,因此我不需要很长的复杂的preg_replace正则表达式,只需一个简单的preg_replacestr_replace规则即可。

I ONLY want to remove JavaScript comments that start with "// " (including the space so I don't erase URLs) up until the new line. 我只想删除以“ //”开头的JavaScript注释(包括空格,因此我不会删除URL)直到新行为止。 THAT'S IT! 而已! Once again, I don't need to replace /* */ or any other variations as I have a script that does that already; 再一次,我不需要替换/ * * /或任何其他变体,因为我已经有一个脚本可以执行此操作; the only thing it's missing is this one feature so I want to clean up the input with this first, then hand it over to the script. 唯一缺少的是此功能,因此我想先清理此输入,然后将其移交给脚本。

Here are screenshots with examples of comments I would like to remove: 以下是我要删除的评论示例的屏幕截图:

屏幕截图1 屏幕截图2

I would really appreciate help with this! 我真的很感谢帮助! :-) THANKS! :-) 谢谢!

Try this code: 试试这个代码:

$re = "~\\n? */{2,} .*~"; 
$str = "text\n\n/*\ntext\n*\n    //example1\n    //example2\n\ntext\n\n//   example 3"; 
$subst = ""; 

$result = preg_replace($re, $subst, $str);

The regex matches two or more / following by a space like you asked in the question. 正则表达式匹配两个或多个/ ,后跟一个空格,就像您在问题中所问的那样。 When you replace it will erase the whole line or until the spaces and line breaks that were 更换时,它将擦除整行或直到原来的空格和换行符为止

Demo 演示

I'd use a regex with the multi-lined modifier , m , 我会使用带有多行修饰符 m的正则表达式

/^\h*\/\/.*$/m

This will find any lines that start with a // regardless of the whitespace preceding it. 这将查找任何以//开头的行,而不管其前面的空格如何。 Anything after the first // will be removed until the end of that line. 第一个//之后的所有内容都将被删除,直到该行的末尾。

Regex101 Demo: https://regex101.com/r/tN7nW9/2 Regex101演示: https ://regex101.com/r/tN7nW9/2

You should include your data in the future as a string (not image) so users can run tests on it. 您将来应该将数据作为字符串(而不是图像)包括在内,以便用户可以对其进行测试。

PHP Usage: PHP用法:

echo preg_replace('/^\h*\/\/.*$/m', '', $string);

PHP Demo: https://eval.in/430182 PHP演示: https : //eval.in/430182

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM