[英]Remove all html tags and javascript tags using regex in javascript
[英]Remove html tags using regex in javascript
我想使用以下代碼從文檔中刪除除<a>
<img>
和<iframe>
之外的所有html標簽:
var regex = "<(?!a )(?!img )(?!iframe )([\s\S]*?)>";
var temp;
while (source.match(regex)) {
temp = source.match(regex)[0];
source = source.replace(temp, "");
}
return source;
它可以在在線正則表達式測試器中使用,但由於某種原因,它在我的頁面上不起作用。 例如,當輸入為:
"<p class="MsoNormal" style="margin-left:202.5pt;line-height:200%;background:white"><b><span style="font-size: 16pt; line-height: 200%; color: rgb(131, 60, 11); background-image: initial; background-attachment: initial; background-size: initial; background-origin: initial; background-clip: initial; background-position: initial; background-repeat: initial;">test</span></b><span style="font-size:16.0pt;
line-height:200%;color:#833C0B;letter-spacing:-.15pt;mso-ansi-language:EN-US"><o:p></o:p></span></p>"
請幫忙!
這是我能想到的最好的!
<((?!a)|a\w)(?!\/a)(?!img)(?!iframe)(?!\/iframe)+([\s\S]*?)>
第一個捕獲組(不是a或后跟一個單詞)允許音頻,縮寫,地址等全部通過。
只需將上面的正則表達式中的匹配項替換為空即可。
請參閱: http : //regexr.com/3a5hp
您可以不使用正則表達式。 嘗試使用正則表達式解析HTML通常不是一個好主意,除非用例非常簡單...
我實現stripHtmlElementsMatching
的方式,可以將其傳遞給任何CSS選擇器,它將剝離所有匹配的實體。
因此,要刪除除a, img, iframe
任何內容a, img, iframe
您可以傳遞:not(a):not(img):not(iframe)
。
PS: htmlstripping-root
自定義標記只是為了避免創建會干擾傳遞的選擇器的解析器元素。 例如,如果我將div
用作解析器元素,並且您將通過選擇器div > div
,則所有div也將被刪除,即使它們未嵌套在html字符串中也是如此。
var stripHtmlElementsMatching = (function(doc) { doc.registerElement('htmlstripping-root'); return function(text, selector) { var parser = document.createElement('htmlstripping-root'), matchingEls, i, len, el; selector = typeof selector == 'string' ? selector : ':not(*)'; parser.innerHTML = text; matchingEls = parser.querySelectorAll(selector); for (i = 0, len = matchingEls.length; i < len; i++) { el = matchingEls[i]; el.parentNode.replaceChild(newFragFrom(el.childNodes), el); } return parser.innerHTML; }; function newFragFrom(nodes) { var frag = document.createDocumentFragment(); while (nodes.length) frag.appendChild(nodes[0]); return frag; } })(document); var text = '<p class="MsoNormal" style="margin-left:202.5pt;line-height:200%;background:white"><b><span style="font-size: 16pt; line-height: 200%; color: rgb(131, 60, 11); background-image: initial; background-attachment: initial; background-size: initial; background-origin: initial; background-clip: initial; background-position: initial; background-repeat: initial;">test</span></b><span style="font-size:16.0pt; line-height:200%;color:#833C0B;letter-spacing:-.15pt;mso-ansi-language:EN-US"><o:p></o:p></span></p>'; var tagsToKeep = ['a', 'img', 'iframe']; var sanitizeSelector = tagsToKeep.map(function(tag) { return ':not(' + tag + ')'; }).join(''); var sanitizedText = stripHtmlElementsMatching(text, sanitizeSelector); document.body.appendChild(document.createTextNode(sanitizedText));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.