gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:32:06 38 4
gpt4 key购买 nike

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

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

/*
Some very important comment
*/

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

最佳答案

one from @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));

使用 RegExr.com :

various tests from RegExr.com using the provided regular expression

关于javascript - 使用 JavaScript 使用 JavaScript 从字符串中删除注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37051797/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com