开发者

escape HTML chracters

I need to HTML encode chracters like my input 开发者_如何转开发is <test> my expected output is &lt;test&gt;.

How can I do this?


var encoded = htmlEncode('<test>');    // returns "&lt;test&gt;"

// ...

function htmlEncode(str) {
    var div = document.createElement('div');
    var txt = document.createTextNode(str);
    div.appendChild(txt);
    return div.innerHTML;
}


Encoder.js

  • htmlDecode: Decodes HTML encoded text to its original state.
  • htmlEncode: Encodes HTML to either numerical or HTML entities. This is determined by the EncodeType property.

HTML encode text from an input element. This will prevent double encoding.

var encoded = Encoder.htmlEncode(document.getElementById('input'));

To encode but to allow double encoding which means any existing entities such as & will be converted to &amp;

var dblEncoded = Encoder.htmlEncode(document.getElementById('input'),true);


You are supposed to use HTML Entities to replicate special characters.


htmlspecialchars() and do your own str_replace() for the html comments


function simpleEscape(str) {
    return str.replace('<', '&lt;').replace('>', '&gt;');
}

var myStr = '<test>';
alert(simpleEscape(myStr));

Easiest I can think of (provided that this is all you intend to replace).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜