第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用javascript從字符串中刪除完整的標記?

如何使用javascript從字符串中刪除完整的標記?

寶慕林4294392 2019-04-10 14:15:56
我的意見如下input = "hello <script>alert("I am stealing your data");</script>"我想從字符串中刪除完整的腳本標記,輸出應該是這樣的output = "hello"試過以下命令,但不刪除完整標記。input.replace(/(<([^>]+)>)/ig, ''));它給我們帶來了結(jié)果"hello alert("I am stealing you data");"
查看完整描述

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傳遞給您的應用程序是一個非常糟糕的主意。清理涉及的不僅僅是刪除腳本標記。


查看完整回答
反對 回復 2019-05-17
?
侃侃爾雅

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>"))


查看完整回答
反對 回復 2019-05-17
  • 2 回答
  • 0 關(guān)注
  • 488 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號