javascript字符串替换<进入<

时间:2011-03-14 17:19:54

标签: javascript jquery replace

嘿所有,我基本上使用jquery:

将内容输出到这样的div中
var text = $("#edit").val();
$("#output").text(text);

但我想转“& lt;”和“& gt;”进入“<”和“>”。

text.replace(/&lt;/,"<");似乎对我不起作用......

有什么想法吗?非常感谢

4 个答案:

答案 0 :(得分:19)

您可以在原型中使用类似unescapeHTML()函数的内容......

改编自prototype js来源

function unescapeHTML(escapedHTML) {
  return escapedHTML.replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');
}

答案 1 :(得分:14)

简单。

var needToConvert = 'But I want to turn "&lt;" and "&gt;" into "<" and ">".';

var convert = function(convert){
    return $("<span />", { html: convert }).text();
    //return document.createElement("span").innerText;
};

alert(convert(needToConvert));

答案 2 :(得分:1)

将其分配给变量:

var text = $("#edit").val();
text = text.replace("&lt;","<");

这样可以正常使用

答案 3 :(得分:1)

您需要使用.html(),因为text()会转换所有html标签

$("#output").html(text);