我有两个像这样的 html 注释:
<!--Delete-->
Blah blah
blah blah
<!--Delete-->
我想删除它(包括注释、任何字符和换行符)。顺便说一句,我正在使用 javascript 和 Grunt 进行替换。
谢谢
最佳答案
正则表达式
使用以下 JavaScript 正则表达式来匹配自定义 .html
的多个实例评论及其内容:
/\<\!\-\-Delete\-\-\>((.|[\n|\r|\r\n])*?)\<\!\-\-Delete\-\-\>[\n|\r|\r\n]?(\s+)?/g
<小时/>
然后注册一个自定义Function Task在你的Gruntfile.js
里面如下要点所示:
Gruntfile.js
module.exports = function (grunt) {
grunt.initConfig({
// ... Any other Tasks
});
grunt.registerTask('processHtmlComments',
'Remove content from inside the custom delete comments',
function() {
var srcDocPath = './src/index.html', // <-- Define src path to .html
outputDocPath = './dist/index.html',// <-- Define dest path for .html
doc = grunt.file.read(srcDocPath, {encoding: 'utf8'}),
re = /\<\!\-\-Delete\-\-\>((.|[\n|\r|\r\n])*?)\<\!\-\-Delete\-\-\>[\n|\r|\r\n]?(\s+)?/g,
contents = doc.replace(re, '');
grunt.file.write(outputDocPath, contents, {encoding: 'utf8'});
console.log('Created file: ' + outputDocPath);
});
grunt.registerTask('default', [
'processHtmlComments'
]);
};
附加说明
当前正在运行$ grunt
通过 CLI 执行以下操作:
- 读取名为
index.html
的文件来自src
文件夹。 - 删除开始和结束自定义注释中的所有内容,
<!--Delete-->
,包括评论本身。 - 写入新的
index.html
,排除不需要的内容,到dist
文件夹。
srcDocPath
的两个值和outputDocPath
可能需要根据您的项目要求重新定义。
编辑更新了正则表达式以允许使用内联注释。例如:
<p>This text remains <!--Delete-->I get deleted<!--Delete-->blah blah</p>
关于javascript - Regex Javascript - 删除两个 html 注释之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42242637/