2017-02-15 39 views

回答

0

正则表达式

使用下面的JavaScript正则表达式匹配您的自定义的多个实例.html意见,并在他们里面的内容:如在

/\<\!\-\-Delete\-\-\>((.|[\n|\r|\r\n])*?)\<\!\-\-Delete\-\-\>[\n|\r|\r\n]?(\s+)?/g 

然后你Gruntfile.js内注册自定义Function Task以下要点:

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' 
    ]); 

}; 

其他注意事项

目前通过CLI运行$ grunt执行以下操作:

  1. 读取一个名为从src文件夹index.html文件。
  2. 删除开始和结束自定义评论<!--Delete-->中的任何内容,包括评论本身。
  3. dist文件夹写入新的index.html(不包括不需要的内容)。

srcDocPathoutputDocPath的值都可能需要根据您的项目要求重新定义。


编辑更新的正则表达式中,也允许联注释使用。例如:

<p>This text remains <!--Delete-->I get deleted<!--Delete-->blah blah</p> 
0

在下面的正则表达式, 我们用一个字请与
\<\! =>开始逃逸=><!
然后(.)*任何东西
后 然后跳过第一个标签结束\-\>
然后anythig (.)*
然后在评论结束时\-\-\>
并检查gl obal match g;

var text="<div>hello there</div><!--Delete-->Blah blahblah blah<!--Delete--><span>Hello world</span>"; 
 
var re=/\<\!(.)*\-\>(.)*\-\-\>/g; 
 
console.log(text.replace(re,""));

但一般HTML注释模样

<!--comments blah blah blah //--> 

的是,这里是另一个正则表达式

var text = "<span>Hi there</span><div>Hello world</div><!--comments blah blah blah //--><span>something</span>"; 
 
var re=/\<\!\-(.)*\/\/\-\-\>/g; 
 
console.log(text.replace(re,""));

相关问题