[英]Remove all html attributes with regex (replace)
例如我有這樣的HTML:
<title>Ololo - text’s life</title><div class="page-wrap"><div class="ng-scope"><div class="modal custom article ng-scope in" id="new-article" aria-hidden="false" style="display: block;"><div class="modal-dialog first-modal-wrapper">< div class="modal-content"><div class="modal-body full long"><div class="form-group">olololo<ul style="color: rgb(85, 85, 85);background-color: rgb(255, 255, 255);"><li>texttext</li><li>Filter the events lists by host.</li><li>Create graphs for separate hosts and for the groups of hosts.</li></ul><p style="color: rgb(85, 85, 85);background-color: rgb(255, 255, 255);">bbcvbcvbcvbcvbcvbcvbcvb</p></div></div></div></div></div></div><title>cvbcbcvbcvbcvbccb</title><div class="page-wrap"></div></div>
我如何從此類html中刪除所有樣式類ID?
我有這樣的正則表達式:
/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i
怎么了? 如何在正則表達式的幫助下刪除所有html屬性?
這里是小提琴:
您不應該在這里使用正則表達式。
var html = '<title>Ololo - text’s life</title><div class="page-wrap"><div class="ng-scope"><div class="modal custom article ng-scope in" id="new-article" aria-hidden="false" style="display: block;"><div class="modal-dialog first-modal-wrapper"><div class="modal-content"><div class="modal-body full long"> <div class="form-group">olololo<ul style="color: rgb(85, 85, 85);background-color: rgb(255, 255, 255);"><li>texttext</li><li>Filter the events lists by host.</li><li>Create graphs for separate hosts and for the groups of hosts.</li> </ul><p style="color: rgb(85, 85, 85);background-color: rgb(255, 255, 255);">bbcvbcvbcvbcvbcvbcvbcvb</p></div><div></div></div></div></div><title>cvbcbcvbcvbcvbccb</title><div class="page-wrap"></div></div>';
var div = document.createElement('div');
div.innerHTML = html;
function removeAllAttrs(element) {
for (var i = element.attributes.length; i-- > 0;)
element.removeAttributeNode(element.attributes[i]);
}
function removeAttributes(el) {
var children = el.children;
for (var i = 0; i < children.length; i++) {
var child = children[i];
removeAllAttrs(child);
if (child.children.length) {
removeAttributes(child);
}
}
}
removeAttributes(div);
console.log(div.innerHTML);
首先,我建議您在這種情況下不要使用正則表達式 ,它們並不意味着解析HTML之類的樹形結構。
但是,如果您別無選擇,我認為對於所要求的問題,可以使用正則表達式。
在我看來,您好像忘記了空格,重音符號等。您可以使用以下事實:不允許將大於>
和小於<
符號用作原始文本。
/<\s*([a-z][a-z0-9]*)\s.*?>/gi
並調用:
result = body.replace(regex, '<$1>')
對於給定的樣本,它將產生:
<title>Ololo - text’s life</title><div><div><div><div><div><div><div>olololo<ul><li>texttext</li><li>Filter the events lists by host.</li><li>Create graphs for separate hosts and for the groups of hosts.</li></ul><p>bbcvbcvbcvbcvbcvbcvbcvb</p></div></div></div></div></div></div><title>cvbcbcvbcvbcvbccb</title><div></div></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.