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

时间:2016-05-05 13:22:53

标签: javascript

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

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

/*
Some very important comment
*/

如何删除“'”中的所有评论。串?我应该使用一些正则表达式吗?我不知道。

5 个答案:

答案 0 :(得分:4)

如果您想使用RegExp,可以使用这个:

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

这应该删除// ... \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

答案 1 :(得分:2)

one from @MarcoS在某些情况下无法使用...

以下是我的解决方法:

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

使用RegExr.com

various tests from RegExr.com using the provided regular expression

答案 2 :(得分:0)

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

(\/\*[\wа-я\'\s\r\n\*]*\*\/)|(\/\/[\wа-я\s\'\;]*)|(\<![\-\-\s\wа-я\>\/]*\>)

RegEX部件:

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 ,在评论中支持俄罗斯符号

&#13;
&#13;
textarea{
  width:300px;
  height:120px;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

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

);

答案 4 :(得分:0)

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不能像多个注释一样删除,只能是一行注释。

如果要删除多行注释,则必须编写解析器。或使用其他非正则表达式。