2 回答

TA貢獻2051條經(jīng)驗 獲得超10個贊
您不應該使用正則表達式。而是使用DOM解析器功能:
var input = 'hello <script\>alert("I am stealing your data");</script\>';
var span = document.createElement("span");
span.innerHTML = input; // This will not execute scripts
// Remove all script tags within this span element:
Array.from(span.querySelectorAll("script"), script => script.remove());
// Get the remaining HTML out of it
var scriptless = span.innerHTML;
console.log(scriptless);
請注意,讓用戶將任意HTML傳遞給您的應用程序是一個非常糟糕的主意。清理涉及的不僅僅是刪除腳本標記。

TA貢獻1801條經(jīng)驗 獲得超16個贊
您不需要使用正則表達式,因為它們很容易欺騙,不適合解析HTML內(nèi)容,尤其是不受信任的HTML內(nèi)容。
相反,您可以使用a DOMParser
創(chuàng)建新文檔并使用DOM API刪除所有腳本標記,然后返回其余內(nèi)容:
function sanitise(input) {
const parser = new DOMParser();
const doc = parser.parseFromString(input, "text/html");
let scripts = [...doc.getElementsByTagName('script')]
scripts.forEach(script => script.remove());
return doc.body.textContent.trim();
}
//using the + because otherwise StackSnippets breaks
console.log(sanitise("hello <script>alert('I am stealing your data');</scr"+"ipt>"))
添加回答
舉報