2011-12-30 74 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