javascript - Regex Javascript - 删除两个 html 注释之间的文本

标签 javascript html regex gruntjs

我有两个像这样的 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 执行以下操作:

  1. 读取名为 index.html 的文件来自src文件夹。
  2. 删除开始和结束自定义注释中的所有内容, <!--Delete--> ,包括评论本身。
  3. 写入新的 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/

相关文章:

javascript - 我在 div 中有一个长表,当我滚动表时,我想看到它惯性移动 HTML

javascript - 在更改第一个选定项时显示第二个下拉菜单

java - 将正则表达式添加到列表中以进行排序

javascript - 正则表达式检查文件是否是图像

javascript - 如何将样式类应用于按钮,但在 Vue 中任何时候只能激活一个按钮?

javascript - 使用 JSON 数据用数据库对象填充 Google map

css - 在 html 5 中,如何将 div 元素定位在 canvas 元素之上?

javascript - 如何将目标 ="_parent"添加到所有菜单项

javascript - 如何使用ajax将STL文件从js发送到没有表单数据的php

c# - 使用正则表达式验证模型