Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

RegEx for match/replacing JavaScript comments (both multiline and inline)

I need to remove all JavaScript comments from a JavaScript source using the JavaScript RegExp object.

What I need is the pattern for the RegExp.

So far, I've found this:

compressed = compressed.replace(//*.+?*/|//.*(?=[

])/g, '');

This pattern works OK for:

/* I'm a comment */

or for:

/*
 * I'm a comment aswell
*/

But doesn't seem to work for the inline:

// I'm an inline comment

I'm not quite an expert for RegEx and it's patterns, so I need help.

Also, I' would like to have a RegEx pattern which would remove all those HTML-like comments.

<!-- HTML Comment //--> or <!-- HTML Comment -->

And also those conditional HTML comments, which can be found in various JavaScript sources.

Thanks.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

NOTE: Regex is not a lexer or a parser. If you have some weird edge case where you need some oddly nested comments parsed out of a string, use a parser. For the other 98% of the time this regex should work.

I had pretty complex block comments going on with nested asterisks, slashes, etc. The regular expression at the following site worked like a charm:

http://upshots.org/javascript/javascript-regexp-to-remove-comments
(see below for original)

Some modifications have been made, but the integrity of the original regex has been preserved. In order to allow certain double-slash (//) sequences (such as URLs), you must use back reference $1 in your replacement value instead of an empty string. Here it is:

//*[sS]*?*/|([^\:]|^)//.*$/gm

// JavaScript: 
// source_string.replace(//*[sS]*?*/|([^\:]|^)//.*$/gm, '$1');

// PHP:
// preg_replace("//*[sS]*?*/|([^\:]|^)//.*$/m", "$1", $source_string);

DEMO: https://regex101.com/r/B8WkuX/1

FAILING USE CASES: There are a few edge cases where this regex fails. An ongoing list of those cases is documented in this public gist. Please update the gist if you can find other cases.

...and if you also want to remove <!-- html comments --> use this:

//*[sS]*?*/|([^\:]|^)//.*|<!--[sS]*?-->$/

(original - for historical reference only)

// DO NOT USE THIS - SEE ABOVE
/(/*([sS]*?)*/)|(//(.*)$)/gm

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...