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

寵の児 提交于 2019-12-31 04:38:07

问题


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.

I ONLY want to remove JavaScript comments that start with "// " (including the space so I don't erase URLs) up until the new line. 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:

I would really appreciate help with this! :-) THANKS!


回答1:


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




回答2:


I'd use a regex with the multi-lined modifier, 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

You should include your data in the future as a string (not image) so users can run tests on it.

PHP Usage:

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

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



来源:https://stackoverflow.com/questions/32462878/how-do-i-remove-only-javascript-comments-that-start-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!