Introduction

In this blog, I am sharing code snippet to escape the HTML from the given string with whitelist tags and special characters.
This code snippet would help you to remove the html/script from the string excluding the whitelisted tagsand special chars so that we can avoid XSS attack.
  1. /*
  2. Function to escape the html with specified whitelist tags & spl chars
  3. @param htmlString string string to be escaped
  4. @param tags string comma separated tag list to be unescaped
  5. @param splChars string comma separated spl char list to be unescaped
  6. @example
  7. var exTags = 'b,p,strong, i';
  8. var exSplChars = '?,!';
  9. document.querySelector('#editor').innerHTML = safeHTML("<strong> Need</strong> tips? <i> Visit </i> <b> W3Schools! </b>", exTags, exSplChars);
  10. */
  11. function safeHTML(htmlString, tags, splChars) {
  12. var exDefaults = ' , %',
  13. pattern = prepareTagsRegExpPattern() + '|' + prepareCharsRegExpString();
  14. return escape(htmlString).replace(new RegExp(pattern, 'ig'), function(match) { return unescape(match); });
  15. function prepareTagsRegExpPattern() {
  16. return (tags || '').split(',').map(function(tag, index, arr) {
  17. var text = '';
  18. tag = tag.trim();
  19. if(index === 0) {
  20. text = '%3C(' + tag + '|' + '/' + tag;
  21. }else if(index === arr.length -1) {
  22. text = tag + '|' + '/' + tag + ')%3E';
  23. } else {
  24. text = tag + '|' + '/' + tag
  25. }
  26. return text;
  27. }).join('|');
  28. }
  29. function prepareCharsRegExpString() {
  30. return (splChars || '').split(',').map(function(char) { return escape(char); }).join('|') + '|' +
  31. (exDefaults || '').split(',').map(function(char) { return escape(char) }).join('|') ;
  32. }
  33. }
Here is more details