2012-09-25 21 views
3

如果你有一個字符串包含HTML實體,並希望取消轉義它,這個解決方案(或其變型)建議多次:在Javascript中包含換行符的Unescape HTML實體?

function htmlDecode(input){ 
    var e = document.createElement('div'); 
    e.innerHTML = input; 
    return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue; 
} 

htmlDecode("<img src='myimage.jpg'>"); 
// returns "<img src='myimage.jpg'>" 

(參見,例如,這樣的回答:https://stackoverflow.com/a/1912522/1199564

這隻要這個串包含換行,我們的Internet Explorer版本上運行預10(9測試版和8)工作正常。

如果字符串包含一個新行,IE 8和9將與一個空格字符,而不是留不變(因爲它是在Chrome,Safari,Firefox和IE 10)替換它。

htmlDecode("Hello\nWorld"); 
// returns "Hello World" on IE 8 and 9 

對於在版本10之前與IE一起使用的解決方案的任何建議?

+0

你怎麼想換行呢?去掉它? – David

+0

我想保持不變。我會添加一個例子。 – mgd

+0

我不確定它是否會完全符合您的需求,但是您是否已檢出此[HTML編碼和解碼JavaScript庫](http://www.strictly-software.com/htmlencode)? – freefaller

回答

4

最簡單的,但可能不是最有效的解決方法是隻對字符和實體引用htmlDecode()行爲:

var s = "foo\n&amp;\nbar"; 
s = s.replace(/(&[^;]+;)+/g, htmlDecode); 

更有效地使用的htmlDecode()優化的重寫僅每個輸入調用一次,只作用於字符和實體引用,並重新使用DOM元素對象:

function htmlDecode (input) 
{ 
    var e = document.createElement("span"); 

    var result = input.replace(/(&[^;]+;)+/g, function (match) { 
    e.innerHTML = match; 
    return e.firstChild.nodeValue; 
    }); 

    return result; 
} 

/* returns "foo\n&\nbar" */ 
htmlDecode("foo\n&amp;\nbar"); 

弗拉基米爾Palant曾指出這一功能的XSS問題:The value of some (HTML5) event listener attributes, like onerror, is executed if you assign HTML with elements that have those attributes specified to the innerHTML property.因此,您不應該在包含實際HTML的任意輸入上使用此函數,只能在已經轉義的HTML上使用此函數。否則,你應該調整相應的正則表達式,例如使用/(&[^;<>]+;)+/而不是防止&…;其中包含相匹配的標籤。

對於任意的HTML,請看他的alternative approach,但請注意它不像這個兼容。

+1

謝謝。奇蹟般有效。我建議你編輯示例字符串「foo &」,以包含「\ n」字符,如「foo \ n & \ nbar」,以說明代碼正確處理換行符。另外,請你解釋爲什麼'e'參與了循環參考。 – mgd

+0

有道理。我想接受你的編輯給你的信用,但我不知道如何,因爲這是第一次有人編輯我的答案之一。我只能看到兩個虛假(?)拒絕,沒有「接受」按鈕: -/ – PointedEars

+0

@mgd顯然,您無法批准已被拒絕的修改,因此我已將您的修改和+1應用於評論。 – PointedEars

相關問題