Created
December 4, 2017 12:35
-
-
Save leoli-dev/ae1e27bc1430dccfa6d672e554bfd9fd to your computer and use it in GitHub Desktop.
PHP HTML entiy functions (`htmlentities()` & `html_entity_decode()`) in jQuery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.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, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); | |
}, | |
/** | |
* 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; | |
})() | |
}; |
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: "<h1>Hello</h1>"
$.htmlentities.decode("<h1>Hello</h1>"); // result: "<h1>Hello</h1>"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found this function, but how does it work?
thanks by advance