escape HTML chracters
I need to HTML encode chracters like my input 开发者_如何转开发is <test>
my expected output is <test>
.
How can I do this?
var encoded = htmlEncode('<test>'); // returns "<test>"
// ...
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 &
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('<', '<').replace('>', '>');
}
var myStr = '<test>';
alert(simpleEscape(myStr));
Easiest I can think of (provided that this is all you intend to replace).
精彩评论