簡體   English   中英

正則表達式Javascript-刪除兩個HTML注釋之間的文本

[英]Regex Javascript - Remove text between two html comments

好吧,我有兩個這樣的html注釋:

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

我想刪除它(包括注釋,任何字符和換行符)。 順便說一句,我正在使用javascript和Grunt進行替換。

謝謝

正則表達式

使用以下JavaScript正則表達式來匹配您的自定義.html注釋及其內部內容的多個實例:

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

然后在您的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'
    ]);

};

補充筆記

當前通過CLI運行$ grunt執行以下操作:

  1. src文件夾中讀取名為index.html的文件。
  2. 從開始和結束自定義注釋<!--Delete-->刪除所有內容,包括注釋本身。
  3. 將新的index.html (不包括不需要的內容)寫入dist文件夾。

可能需要根據您的項目要求重新定義srcDocPathoutputDocPath的值。


編輯更新了正則表達式,也允許使用內聯注釋。 例如:

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

在下面的正則表達式中,我們以單詞開頭
\\<\\! =>轉義后=> <!
然后(.)*執行任何操作
然后跳過第一個標簽結尾\\-\\>
然后anythig (.)*
然后在評論末尾\\-\\-\\>
並檢查全局匹配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,"")); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM