2011-12-30 75 views
0

嗯,我var message,這有什麼類型的角色......嵌入HTML篩選

<a href="...">...</a>

然後替換:)與<img src="..." .../>http://www.youtube.com/watch?v=id我跑$(".chat_message").html(message);

我必須是否嵌入任何東西,除了html標籤,我作爲html代碼屏幕?

+0

這個問題對我來說有點糾結。可以將整個站點縮減爲「腳本src」標籤。如果您想嵌入視頻檢查動態對象模型(DOM)。 – rekire 2011-12-30 23:11:36

回答

0

我必須做什麼才能嵌入除html標籤之外的任何東西,我將其作爲html代碼來屏蔽?

我打算假設你想要message中的每個字符,除了用HTML標記替換的字符在字面上顯示在屏幕上。

var messageHTML = message.replace(/&/g, "&amp;") 
    .replace(/</g, "&lt;").replace(/>/g, "&gt;"); 

將把HTML相當於messagemessageHTML *。

一旦messageHTML包含一串HTML,您可以安全正確地替換所有出現的":)",因爲這只是一個簡單的HTML - > HTML轉換。

messageHTML = messageHTML.replace(/:\)/g, "<img ...>"); 

現在你可以使用jQuery的.html(messageHTML)注入message與標記到DOM。

* - 白色的空間將是不同的,除非你是在上下文中使用CSS white-space: prewhite-space: pre-wrap

+0

正是我想要的! Thx !! – 2011-12-30 23:15:45

0

刺在黑暗中嵌入(你的問題不是很清楚)。這需要在一個字符串,替換所有ASCII代碼的HTML標籤,有點怪異的一部分,然後抓住該消毒的輸出,增加了笑臉圖像:

var message = $('<p>stuff in <span>here</span> :)</p>').html(); 
$(".chat_message").text(message); 
$(".chat_message").html($('.chat_message').html().replace(/:\)/g, "<img />")); 

這裏是一個演示:http://jsfiddle.net/5fT5b/1/

0

以下例如處理的網站的URL和非ASCII字符:

var message = "My name is Andy :) - and my fav web-site is http://stackoverflow.com"; 

//Protect against HTML characters (you might want to add more). 
message=message 
    .replace("&", "&amp;") 
    .replace("<", "&lt;") 
    .replace("<", "&gt;"); 

//Protect against non-ASCII characters. 
message=message 
    .replace(/[\x80-\xff]/, "*"); 

//Handle smilies. 
message=message 
    .replace(":)", '<img src="..." />'); 

//Handle embedded web-site addresses. The "$0" bit says to repeat the matched thing. 
//The "https?" matches "http" and "https". If you want something smarter then check out 
//http://www.w3schools.com/js/js_obj_regexp.asp 
message=message 
    .replace(/https?:[^ ]+/g, '<a href="$0">$0</a>'); 

$(".chat_message").html(message); 

我依稀記得閱讀正確HTML編碼的文本,並且有一串字符以上ASCII 128有可能被用於注入腳本。 [\ x80- \ xff]位應該防止這些。

+0

'.replace(「<」,「>」);'是一個複製粘貼錯誤,即使它被修復了,它仍然會被破壞。 '「<<」。replace(「<」,「>」)==「> <」'因爲替換爲一個字符串只會替換* first *發生。 – 2011-12-31 21:02:31