【问题标题】:Remove comments from string with JavaScript using JavaScript使用 JavaScript 从字符串中删除注释
【发布时间】:2016-08-31 07:29:33
【问题描述】:

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

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

/*
Some very important comment
*/

如何从 's' 字符串中删除所有 cmets?我应该使用一些正则表达式吗?我不知道。

【问题讨论】:

标签: javascript


【解决方案1】:

one from @MarcoS 在某些情况下不起作用...

以下是我的解决方案:

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

从字符串中删除 cmets:

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));

使用RegExr.com

【讨论】:

  • 您是否可以编辑您的答案以显示完整的 JS 功能?
  • @DanielL.VanDenBosch 我已经编辑了答案以包含完整的功能!
【解决方案2】:

如果你想使用正则表达式,你可以使用这个:

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

这应该同时去除 // ... \n 样式 cmets 和 /* ... */ 样式 cmets。

完整的工作代码:

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

【讨论】:

  • @MarkoS,你能给我提供完整的 JS 代码吗?
  • 我收到错误“SyntaxError: Invalid regular expression: /(/*([^*]|[ ]|(+([^*/]|[ ])))* *+/)|(//.)/: 没什么可重复的”@MarkoS
  • 你是对的,抱歉...刚刚用更简单、更短且始终有效的代码更新了答案... :-)
  • 对不起,你的答案不支持多行/**/评论,可以加一下吗?谢谢!
  • 刚刚测试过,它似乎也可以与多行 cmets 一起使用...您失败的测试是什么?
【解决方案3】:

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, '/')

);

【讨论】:

  • 不处理后面没有任何内容的 cmets,例如 // 单独一行,但我真的很喜欢忽略引号内的 cmets 的支持。如果您将第二步替换为已接受的答案,那就更好了。
【解决方案4】:

您可以使用此 RegEX 来匹配所有 cmets (支持俄罗斯符号。| 拉丁文或西里尔文 | )

(\/\*[\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: <!-- .....  -->

Updated Regex101 DEMO

Updated JsFiddle DEMO ,在 cmets 中支持 俄罗斯符号


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 好的,我已经更新了Jsfiddle 和我的回答中的 sn-p
  • @malcoauri 你试过我上次更新的fiddle 之前的评论吗?有什么问题吗?
【解决方案5】:
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 基于正则语法。这意味着常规语法解析器是一个最终状态机,不能保存状态,所以正则表达式不能像多条评论一样删除它只能单行评论。

如果你想删除多行注释,那么你必须编写解析器。或使用其他不是正则表达式的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-19
    • 2012-01-27
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 2013-08-05
    相关资源
    最近更新 更多