我想通过JavaScript函数将文本显示为HTML。如何在JavaScript中转义HTML特殊字符?有API吗?


当前回答

试试这个,使用prototype.js库:

string.escapeHTML();

尝试演示

其他回答

我想我找到了正确的方法……

// Create a DOM Text node:
var text_node = document.createTextNode(unescaped_text);

// Get the HTML element where you want to insert the text into:
var elem = document.getElementById('msg_span');

// Optional: clear its old contents
//elem.innerHTML = '';

// Append the text node into it:
elem.appendChild(text_node);

你可以对字符串中的每个字符进行编码:

function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}

或者只关注主要角色(&,inebreaks, <, >, "和'),比如:

函数编码(r) { 返回r.replace (/ [\ x26 \ x0A \ < > "] / g函数(r){返回" & # + r.charCodeAt(0) +”;“}) } 测试。value=encode('如何编码\nonly html标签&<>\'" nice & fast!'); /************* * \x26是& &号(必须排在第一位), * \x0A为换行符, *************/ < textarea测试行id = =“9”关口= " 55 " > & # 119;& # 119;& # 119;& # 46;& # 87;& # 72;& # 65;& # 75;& # 46;& # 99;& # 111;& # 109;textarea > < /

使用Lodash:

_.escape('fred, barney, & pebbles');
// => 'fred, barney, &amp; pebbles'

源代码

试试这个,使用prototype.js库:

string.escapeHTML();

尝试演示

你可以使用jQuery的.text()函数。

例如:

http://jsfiddle.net/9H6Ch/

来自jQuery文档关于.text()函数:

我们需要意识到这种方法 转义提供的字符串 必须这样才能渲染 正确的HTML格式。为了做到这一点,它调用 DOM方法。createtextnode () 不会将字符串解释为HTML。

以前版本的jQuery文档是这样写的(强调添加):

我们需要知道这个方法在必要时转义提供的字符串,以便在HTML中正确呈现。为此,它调用DOM方法. createtextnode(),该方法将特殊字符替换为对应的HTML实体(例如&amplt表示<)。