使用JavaScript从字符串中删除注释

13

有一些字符串(例如,'s'):

import 'lodash';
// TODO import jquery
//import 'jquery';

/*
Some very important comment
*/
我该如何从字符串“s”中删除所有注释?应该使用正则表达式吗?我不知道。
如何从字符串“s”中删除所有注释?是否需要使用正则表达式?我不确定。

你展示的代码是字符串的内容吗? - MarcoS
是的,它是的,它的字符串值 - malcoauri
1
一个正则表达式可以匹配大多数情况,但是请参考这个链接(http://james.padolsey.com/javascript/removing-comments-in-javascript/)获取更多的见解。 - Moob
另外:https://dev59.com/CnA65IYBdhLWcg3w4C-j - Moob
UglifyJS有删除注释的功能。https://github.com/mishoo/UglifyJS2 - Aleksander Azizi
显示剩余2条评论
6个回答

23

MarcoS的答案在某些情况下无法使用...

以下是我的解决方案:

str.replace(/\/\*[\s\S]*?\*\/|(?<=[^:])\/\/.*|^\/\/.*/g,'');

从字符串中移除注释:

function removeComments(string){
    //Takes a string of code, not an actual function.
    return string.replace(/\/\*[\s\S]*?\*\/|(?<=[^:])\/\/.*|^\/\/.*/g,'').trim();//Strip comments
}
const commentedcode = `
alert('hello, this code has comments!')//An alert
/* A block comment here */
// A single line comment on a newline
`;
console.log(removeComments(commentedcode));

演示:

正则表达式例子

编辑: 我更改了公式以避免链接问题(参见评论


1
你能否编辑你的回答,展示一个完整的JS函数? - Daniel L. VanDenBosch
1
@DanielL.VanDenBosch 我已经编辑了答案,包括完整的函数! - Explosion
\const x = '// hello \n/hello/'`.replace(//*[\s\S]*?*/|//.*/g,'');will getconst x = '\n'` - lisonge
1
这也会删除字符串内部的 //,这会影响例如 "http://.." 这样的 URL。 - Johncl
确实 @Johncl … 我更新了表达式。 - AymKdn
在注释处添加空格。 - Rehmat

7

如果您想使用正则表达式,可以使用以下表达式:

/(\/\*[^*]*\*\/)|(\/\/[^*]*)/

这段代码可以去除两种类型的注释:// ... \n/* ... */

完整的可用代码:

var stringWithoutComments = s.replace(/(\/\*[^*]*\*\/)|(\/\/[^*]*)/g, '');
console.log(stringWithoutComments);

测试多行字符串:

var s = `before
/* first line of comment
   second line of comment */
after`;
var stringWithoutComments = s.replace(/(\/\*[^*]*\*\/)|(\/\/[^*]*)/g, '');
console.log(stringWithoutComments);

输出:

before

after

我收到了错误消息:“SyntaxError: Invalid regular expression: /(/([^]|[ ]|(+([^/]|[ ])))**+/)|(//.*)/: Nothing to repeat” @MarkoS - malcoauri
你说得对,抱歉...我刚刚更新了答案,用更简单、更短和始终有效的代码... :-) - MarcoS
抱歉,但是你的答案不支持多行/**/注释,你能添加一下吗?谢谢! - malcoauri
这个怎么样:// console.log(1*2) - blackmiaool
1
"ok = '// hi';".replace(/(\/\*[^*]*\*\/)|(\/\/[^*]*)/g, ''); will give "ok = '" - nonopolarity
显示剩余3条评论

5

console.log(`

     var myStr = 'я! This \\'seems\\' to be a // comment'; // but this is actually the real comment.
    /* like this one */ var butNot = 'this "/*one*/"'; // but this one and /* this one */
    /* and */ var notThis = "one '//but' \\"also\\""; /* // this one */
    `
    
    // 1) replace "/" in quotes with non-printable ASCII '\1' char
    .replace(/("([^\\"]|\\")*")|('([^\\']|\\')*')/g, (m) => m.replace(/\//g, '\1'))
    
    // 2) clear comments
    .replace(/(\/\*[^*]+\*\/)|(\/\/[^\n]+)/g, '')
    
    // 3) restore "/" in quotes
    .replace(/\1/g, '/')

);


不过它无法处理那些后面没有内容的注释,比如单独一行的 //,但我真的很喜欢它支持忽略引号内的注释。如果你用被接受的答案替换第二步,这会更好。 - phyatt

1
你可以使用这个 正则表达式 来匹配所有的评论 (支持俄罗斯符号 | 拉丁或西里尔文 | )
(\/\*[\wа-я\'\s\r\n\*]*\*\/)|(\/\/[\wа-я\s\'\;]*)|(\<![\-\-\s\wа-я\>\/]*\>)

正则表达式部分:

Part1: (\/\*[\wа-я\'\s\r\n\*]*\*\/) for comments style: /*   .....   */ 

Part2: (\/\/[\wа-я\s\'\;]*)         for comments style: //   .....

Part3: (\<![\-\-\s\wа-я\>\/]*\>)    for comments style: <!-- .....  -->

更新的Regex101演示

更新的JsFiddle演示,支持在注释中使用俄罗斯符号


textarea{
  width:300px;
  height:120px;
}
<textarea id="code">
import 'lodash';
// TODO импортируем auth provider
//import 'jquery';

/*
Some very important comment
*/
</textarea>
<br />
<button onclick="removeAllComments()">Remove All Comments</button>

<script>
    function removeAllComments(){
        var str = document.getElementById('code').innerHTML.replace(/(\/\*[\wа-я\'\s\r\n\*]*\*\/)|(\/\/[\wа-я\s\'\;]*)|(\<![\-\-\s\wа-я\>\/]*\>)/ig, "");
        document.getElementById('code').innerHTML = str;
    }
</script>


你能提供完整的JS代码吗?当然要附带测试,因为它对我来说不起作用。 - malcoauri
@malcoauri 好的,我已经更新了Jsfiddle和我的答案片段。 - Shady Alset
@malcoauri,你试过我在之前评论中更新的fiddle了吗?有什么问题吗? - Shady Alset

1
comment1 = ' I dont like oneline comment. to parsing. // like this comment.'
comment2 = ' also i hate multiple line comment
    /*
    like
    this.*/'

comment1.replace(/\s*(?:\/\/).*?$/gm , '')
// but you can't delete multiple line commet with regular grammar. like comment2

RegExp基于正则语法。这意味着正则语法解析器是一个有限状态机,无法保存状态,因此regexp不能像多行注释一样删除,只能使用单行注释。

如果您想删除多行注释,则必须编写解析器或使用其他工具而不是regexp。


1

我觉得这个非常有用且简洁的解决方案。

const word = ` 
      /**  @page type
      *       page    = ".page-body"
      *       popup   = ".pop-up-body"
      *       overlay = ".overlay-body" // new classes
      * 
      */
     
 
    return {
      "static" : '.page-body, .overlay-body, .pop-up-body, .card-wrapper { margin : 5px !important } .row { padding: 5px !important}'
    }
  `
console.log(word.replace(/\/*[^*]*.[^]*\//g,''))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接