Use js to process HTML entities

Source: Internet
Author: User

Sometimes we may have to use js to process HTML entities. For example& Gt;This content is converted>Symbol, or the opposite operation. If you encounter such a requirement unfortunately, the following content may be helpful.

The implementation of unescapehtmlentities is very simple. Create a node element, write the string to the innerhtml attribute of the element, and return the text content of the element. Passing parameters when calling the following functions'& Gt ;', The result will be'>'

function unescapeHtmlEntities(str) {var tempEle = document.createElement("div");tempEle.innerHTML = str;var result = tempEle.childNodes[0].nodeValue;return result;}

The process of escapehtmlentities is the opposite. When an element is created, a text node is inserted, and the innerhtml of the element is read, the entity of the character is obtained. Passing parameters when calling the following functions'>', The result will be'& Gt ;'

function escapeHtmlEntities(str) {var tempEle = document.createElement("div");tempText = document.createTextNode(str);tempEle.appendChild(tempText);var result = tempEle.innerHTML;return result;}alert(escapeHtmlEntities('>'));  // result : >

If jquery is used, the two functions can be completed in one sentence:

function unescapeHtmlEntities(str) {    return $('<div />').html(str).text();}
function escapeHtmlEntities(str){    return $('<div />').text(str).html();}

However, processing HTML entities is not recommended in the behavior layer.In fact, templates and backend languages can work better, such as htmlentities of PHP:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.