簡體   English   中英

JS RegExp刪除所有HTML標記及其內容?

[英]JS RegExp to remove all HTML tags and their content?

例如,我需要從中獲取:

Before Bold <b>In Bold</b> After Bold

要得到:

Before Bold After Bold.

我試過了:

string.replace(/<.*>.*<\/.*>/,'')

但是它沒有按預期工作。

嘗試這個:

string.replace(/<([^>]+?)([^>]*?)>(.*?)<\/\1>/ig, "")

它為我工作。

看到它在這里工作

var div = document.createElement("div"),
    result = "",
    child;

div.innerHTML = str;
child = div.firstChild;

do {
    if (child.nodeType === 3) {
        result += child.nodeValue;
    }
} while (child = child.nextSibling);

console.log(result);

我不確定正則表達式,但是使用jQuery,您可以輕松刪除子項並使用經典的單行代碼返回HTML:

string = $('<div>').html(string).children().remove().end().html();

暫無
暫無

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

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