2012-02-28 66 views
0

我有字符串,它豐富的文字內容更好的方式來寫這個逃跑的HTML內容

這樣的事情,例如

<p>Hello</p> 

<br/> 

<p> Christian </p> 

<pre> Don't Know what to do </pre> 

現在我想不想腳本存在於上述內容,如果目前esape它

所以如果我有它的內容是這樣的

<p>Hello</p> 

<br/> 

<p> Christian </p> 
<script type="text/javascript"> alert("Hello")</script> 
<pre> Don't Know what to do </pre> 

需要與

<p>Hello</p> 

<br/> 

<p> Christian </p> 
&lt;script type="text/javascript"&gt; alert("Hello")&lt;/script&gt; 
<pre> Don't Know what to do </pre> 

我當前已開發的正則表達式爲它

所以我的代碼看起來像這樣

if content.match(/<script(.+?)>/) { 
    content = content.replace(content.match(/<script(.+?)>/)[0],content.match(/<script(.+?)>/)[0].replace("<","&lt;").replace(">","&gt;")) 
} 
if content.match(/<\script\s*>/) 
{ 
content = content.replace(content.match(/<\/script\s*>/)[0],content.match(/<\/script\s*>/)[0].replace("<","&lt;").replace(">","&gt;")) 
} 

這樣結果的內容將有腳本標籤逃脫

更換

任何人都可以建議我更乾淨的方式來實現這一目標嗎?

+0

HTML sanitisation不是一個簡單的問題:例如,請參閱http://blog.stackoverflow.com/2008/06/safe-html-and-xss/。我建議至少在嘗試編寫自己的代碼之前查看其他代碼。 – 2012-02-28 09:38:01

回答

1

清潔:

content = content.replace(/<(script[^>]*|\/script)>/g, '&lt;$1&gt;'); 

然而,這可能是去了解這個問題的方法。爲什麼這些<script>標籤在JS字符串中處於第一位?

+0

謝謝@jensgram,我正在使用markitup富文本編輯器,我希望阻止腳本標記我知道或不知道粘貼或編寫它們 – Viren 2012-02-28 09:59:33

0

不是你要找的答案,但如果JavaScript被禁用會怎麼樣?你打算讓非轉義的內容出現在頁面上嗎? 希望不是

逃逸必須做到用一個服務器端腳本像PHPASP.NET

如PHP中,htmlentities()[docs here]會做得很好

$escaped = htmlentities($content) 
0

我認爲你應該逃避那些卡拉服務器端。例如在PHP中使用htmlentities

+0

OMG,多數民衆贊成在我這麼愚蠢...寫addslashes()哈哈。感謝您提供正確的解決方案。 – Starx 2012-02-28 09:48:45

相關問題