![](/img/trans.png)
[英]Remove all HTML tags from a html body except <a>, <br>, <b> and <img>
[英]Remove all html tags except <img> or <img/> tags with javascript
我有一個 JS 字符串,我想防止在我的網站消息輸入中注入 html 和 js。
如何從字符串中刪除除 img 標簽之外的所有 HTML 標簽,因為它用於顯示這樣的表情符號:
<img class="emo" src="images/emo/smile.png">
我正在使用以下代碼刪除所有 html 標簽,但它僅適用於<br>
標簽而不適用於 img 標簽。
function remove_tags(html)
{
var html = html.replace("<img>","||img||");
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
html = tmp.textContent||tmp.innerText;
return html.replace("||img||","<img>");
}
要么刪除這些 html 標簽,要么簡單地將它們顯示為簡單的文本,例如: <script> alert("hi");</script>
但除了<img>
標簽。
你可以使用 jQuery 這樣做:
function remove_tags(html)
{
var html = html.replace("<img>","||img||");
var text = jQuery(html).text();
return text.replace("||img||","<img>");
}
你可以使用這個簡單的代碼
var html = '<img class="emo" src="images/emo/smile.png">';
var text = html.replace(/<.*?>/g, "");
replace
方法刪除字符串中的所有 html 標簽。
您可以在底部演示中測試每個 html 字符串。
$("button").click(function(){ var html = $("textarea").val(); var text = html.replace(/<.*?>/g, ""); $("textarea").val(text); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea><img src=x onerror=alert("Test") /><p>aa</p></textarea> <br /> <button>Remove HTML tags</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.