CUTCODEDOWN
Minimalist Semantic Markup

Welcome Guest
Please Login or Register

If you have registered but not recieved your activation e-mail in a reasonable amount of time, or have issues with using the registration form, please use our Contact Form for assistance. Include both your username and the e-mail you tried to register with.

Author Topic: JavaScript: htmlSpecialChars  (Read 746 times)

Jason Knight

  • Administrator
  • Hero Member
  • *****
  • Posts: 1054
  • Karma: +188/-1
    • CutCodeDown -- Minimalist Semantic Markup
JavaScript: htmlSpecialChars
« on: 24 Oct 2019, 07:46:08 pm »
Just going through all my little libraries, and found this tiny gem that's been quite useful.

Code: [Select]
function htmlSpecialChars(str) {
return str.replace(/[&<>"']/g, function(m) {
return '&#38;#38;#' + m.charCodeAt() + ';';
});
}

Nothing fancy, but it works. It escapes enough characters to make an HTML string not render as code should you be forced to innerHTML or other wise slop it into the document.

*** NOTE *** when possible if this is a issue, try to use Element.textContent or document.createTextNode instead of this. Still it's nice to have for when decisions about whether or not to go full Gungan with innerHTML is out of your hands.
We are all, we are all, we are all FRIENDS! For today we're all brothers, tonight we're all friends. Our moment of peace in a war that never ends.

 

SMF spam blocked by CleanTalk

Advertisement