【问题标题】:Regex Javascript - Remove text between two html comments正则表达式 Javascript - 删除两个 html 注释之间的文本
【发布时间】:2017-02-15 07:02:44
【问题描述】:

我有两个这样的 html cmets:

<!--Delete-->
Blah blah
blah blah
<!--Delete-->

我想删除它(包括 cmets、任何字符和换行符)。顺便说一句,我正在使用 javascript 和 Grunt 进行替换。

谢谢

【问题讨论】:

    标签: javascript html regex gruntjs


    【解决方案1】:

    正则表达式

    使用以下 JavaScript 正则表达式来匹配您的自定义 .html cmets 的多个实例以及其中的内容:

    /\<\!\-\-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. 从开始和结束的自定义 cmets &lt;!--Delete--&gt; 中删除任何内容,包括 cmets 本身。
    3. 将新的index.html(不包括不需要的内容)写入dist 文件夹。

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


    EDIT 更新了正则表达式,也允许使用内联注释。例如:

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

    【讨论】:

      【解决方案2】:

      在下面的正则表达式中, 我们检查一个单词开头
      \&lt;\! => 转义后 => &lt;!
      然后(.)* 任何事情
      然后跳过第一个标签结束\-\&gt;
      然后随便(.)*
      然后在评论末尾\-\-\&gt;
      并检查全局匹配 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 cmets 看起来像

      <!--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,""));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-04
        • 2011-05-16
        • 1970-01-01
        • 2010-11-08
        • 1970-01-01
        • 2011-05-02
        • 1970-01-01
        • 2011-08-17
        相关资源
        最近更新 更多