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

mal*_*uri 4 javascript

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

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

/*
Some very important comment
*/
Run Code Online (Sandbox Code Playgroud)

如何删除“ s”字符串中的所有注释?我应该使用一些正则表达式吗?我不知道。

Aym*_*Kdn 12

从@MarcoS一个不会在几种情况下工作...

以下是我的解决方案:

str.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,'');
Run Code Online (Sandbox Code Playgroud)

从字符串中删除注释:

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));
Run Code Online (Sandbox Code Playgroud)

使用RegExr.com

使用提供的正则表达式从 RegExr.com 进行各种测试


Mar*_*coS 5

如果要使用RegExp,可以使用以下一种:

/(\/\*[^*]*\*\/)|(\/\/[^*]*)/
Run Code Online (Sandbox Code Playgroud)

这应该同时删除// ... \n样式注释和/* ... */样式注释。

Full working code:

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

Test with multiline strings:

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

outputs:

before

after
Run Code Online (Sandbox Code Playgroud)


Abd*_*dın 5

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

\n