[英]Javascript regexp replace of multiline content between two tags (including the tags)
在字符串中
some text <p id='item_1' class='item'>multiline content\r\n\r\n for <br/>remove</p><br clear='all' id='end_of_item_1'/><p id='item_2' class='item'>another multiline content\r\n\r\n</p><br clear='all' id='end_of_item_2'/>
我需要刪除
<p id='item_1' class='item'>multiline content\r\n\r\n for <br/>remove</p><br clear='all' id='end_of_item_1'/>
找不到方法如何做到這一點。
var id = 'item_1';
var patt=new RegExp("<p id='"+id+"'(.)*|([\S\s]*?)end_of_"+id+"'\/>","g");
var str="some text <p id='item_1' class='item'>multiline content\r\n\r\n for <br/>remove</p><br clear='all' id='end_of_item_1'/><p id='item_2' class='item'>another multiline content\r\n\r\n</p><br clear='all' id='end_of_item_2'/>";
document.write(str.replace(patt,""));
結果是
some text for
<br>
remove
<p></p>
<br id="<p id=" class="item" clear="all" item_2'="">
another multiline content
<p></p>
<br id="end_of_item_2" clear="all">
請幫助解決這個問題。
為什么不能使用 DOM API 來刪除它? (將所有內容添加到文檔中,然后刪除不需要的內容)
var item1 = document.getElementById('item_1'),
endOfItem1 = document.getElementById('end_of_item_1');
item1.parentNode.removeChild(item1);
endOfItem1.parentNode.removeChild(endOfItem1);
我需要從你的問題中假設一些不言而喻的限制,才能讓它發揮作用:
我猜對了嗎,你想要一個正則表達式,它可以找到(然后替換)任何具有特定 id 的“p”標簽,直到某個標簽(如“br”標簽),id 為“end_of_” [第一個]'?
如果這是正確的,那么以下正則表達式可能對您有用。 可能需要稍微修改一下,讓 JS 接受它:
<p\s+id='([a-zA-Z0-9_]+)'.*?id='end_of_\1'\s*\/>
這將為您提供具有上述標准的任何星座,以及如果 id 為組 1 的名稱,現在應該是一項簡單的任務,檢查 group1 是否包含您要刪除的 id,然后將整個匹配替換為空字符串。
如果我理解您的示例正確性(我對 JavaScript 不太擅長,而且我的 RegEx 是基於一般的 perl-regex 時尚),您可能會執行以下操作:
var patt=new RegExp("<p\s+id='"+id+"'.*?id='end_of_"+id+"'\s*\/>","g");
這樣,您不必擔心組匹配,盡管我發現它更優雅,通過組匹配您想要的 id 而不是將其插入到 RegEx 中。
這是當前場景的正則表達式。 當正則表達式方法最終失效時,請記住我們警告過使用正則表達式解析 HTML 是愚蠢的差事。 ;)
這個:
var s = "some text <p id='item_1' class='item'>multiline content\r\n\r\n for <br/>remove</p><br clear='all' id='end_of_item_1'/><p id='item_2' class='item'>another multiline content\r\n\r\n</p><br clear='all' id='end_of_item_2'/><ul><li>";
var id = 'item_1';
var patt = new RegExp ("<p[^<>]*\\sid=['\"]" + id + "['\"](?:.|\\n|\\r)*<br[^<>]*\\sid=['\"]end_of_" + id + "['\"][^<>]*>", "ig")
var stripped = s.replace (patt, "");
產生這個:
"some text <p id='item_2' class='item'>another multiline content
</p><br clear='all' id='end_of_item_2'/><ul><li>"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.