Wednesday, 2 September 2015

Xml and HTML character entity

https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
http://dev.w3.org/html5/html-author/charref
http://www.w3schools.com/html/html_entities.asp
http://www.w3schools.com/html/html_symbols.asp


escape(str);
unescape(str_esc)
escape("<")
>>"%3C"
escape("£")
>>"%A3"
unescape("%A3")
>>"£"
unescape("&pound;")
>>"&pound;"


encodeURI
decodeURI

encodeURI("<")
>>"%3C"
decodeURI("%3C")
>>"<"
encodeURI("£")
>>"%C2%A3"
decodeURI("&pound;")
>>"&pound;"


encodeURIComponent
decodeURIComponent

encodeURIComponent("<")
>>"%3C"
encodeURIComponent("%3C")
>>"%253C"
decodeURIComponent("%3C")
>>"<"
encodeURIComponent("£")
>>"%C2%A3"
decodeURIComponent("&pound;")
>>"&pound;"

They all do the same thing -- convert special characters.

However, &pound; is a Xml and HTML character entity, No JS api can convert it.

But browser can automatically do this it you show "&pound;" in the page, it will automatically displayed as "£".

So, one of the solution is dynamically create a html element and put "&pound;" in it and read text or innerHTML from it.

However, you don't have to append it element to document, you assign to innerHTML and read it out after.

<!DOCTYPE html>
<html>
<body>

<p>Click the button to create a P element with some text, and append it to the document's body.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var x = document.createElement("P");
    x.innerHTML = "&pound;";
    console.log(x.innerHTML);
    //document.body.appendChild(x);
}
</script>

</body>
</html>






The code must run in bowser, which means Nodejs doesn't work






No comments:

Post a comment