爲什麼不使用正則表達式在清理後刪除所有HTML標記?
var input = '<b>hello</b><img src="http://google.com"><a href="javascript:alert(0)"><script src="http://www.google.com"></script>';
var output = null;
output = html_sanitize(input);
output = output.replace(/<[^>]+>/g, '');
這應該消毒後剝去所有 HTML標籤您輸入的字符串。
如果您只想進行基本的清理(只刪除腳本和樣式標記及其內容和所有html標記),則可以在正則表達式中實現整個事件。我已經在下面演示了一個例子。
var input = '<b>hello</b><img src="http://google.com"><a href="javascript:alert(0)"><script src="http://www.google.com"></script>';
input += '<script> if (1 < 2) { alert("This script should be removed!"); } </script><style type="text/css">.cssSelectorShouldBeRemoved > .includingThis { background-color: #FF0000; } </style>';
var output = null;
output = input.replace(/(?:<(?:script|style)[^>]*>[\s\S]+?<\/(?:script|style)[^>]*>)|<[^>]+>/ig, '');
在這一點上,爲什麼不把它作爲一個XML文檔並獲得的innerText? –
我想在我正在編寫的程序中使用bb代碼實現實時預覽。因此,首先我要刪除所有的HTML標籤,然後將BB代碼轉換爲HTML –
那麼爲什麼不把它當作XML文檔並獲取innerText呢? –