Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

javascript - 使用JavaScript使用JavaScript从字符串中删除注释(Remove comments from string with JavaScript using JavaScript)

There is some string (for example, 's'):(有一些字符串(例如,“ s”):)

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

/*
Some very important comment
*/

How can I remove all comments from 's' string?(如何删除“ s”字符串中的所有注释?)

Should I use some Regexp for it?(我应该使用一些正则表达式吗?) I don't know.(我不知道。)   ask by malcoauri translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to use a RegExp, you could use this one:(如果要使用RegExp,可以使用以下一种:)

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

This should strip both // ... \n style comments and /* ... */ style comments.(这应该去除// ... \n样式注释和/* ... */样式注释。)

Full working code:(完整的工作代码:)

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

Test with multiline strings:(用多行字符串测试:)

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

outputs:(输出:)

before

after

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...