Skip to content

Instantly share code, notes, and snippets.

@leoli-dev
Created December 4, 2017 12:35
Show Gist options
  • Save leoli-dev/ae1e27bc1430dccfa6d672e554bfd9fd to your computer and use it in GitHub Desktop.
Save leoli-dev/ae1e27bc1430dccfa6d672e554bfd9fd to your computer and use it in GitHub Desktop.
PHP HTML entiy functions (`htmlentities()` & `html_entity_decode()`) in jQuery
$.htmlentities = {
/**
* Converts a string to its html characters completely.
* It's equivalent to htmlentities() in PHP
* Reference: https://css-tricks.com/snippets/javascript/htmlentities-for-javascript/
*
* @param {String} str String with unescaped HTML characters
**/
encode (str) {
return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
},
/**
* Converts an html characterSet into its original character.
* It's equivalent to html_entity_decode() in PHP
* Reference: https://stackoverflow.com/questions/5796718/html-entity-decode
*
* @param {string}
* @return {string}
**/
decode: (() => {
// this prevents any overhead from creating the object each time
let element = document.createElement('div');
function decodeHTMLEntities(str) {
if (str && typeof str === 'string') {
// strip script/html tags
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
}
return str;
}
return decodeHTMLEntities;
})()
};
@Stefvw26
Copy link

Stefvw26 commented Apr 1, 2020

I found this function, but how does it work?
thanks by advance

@leoli-dev
Copy link
Author

leoli-dev commented Apr 1, 2020

I found this function, but how does it work?
thanks by advance

Hello, this function is easy to use, it required you included jquery first. Then put this function in, and it will work.

I can give you some examples:

$.htmlentities.encode('<h1>Hello</h1>');    // result: "&lt;h1&gt;Hello&lt;/h1&gt;"
$.htmlentities.decode("&lt;h1&gt;Hello&lt;/h1&gt;");    // result: "<h1>Hello</h1>"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment