Last active
July 14, 2016 13:02
-
-
Save jaganathanb/4a84558d75e0892482f70d39aa0c16f3 to your computer and use it in GitHub Desktop.
Revisions
-
jaganathanb revised this gist
Jul 14, 2016 . No changes.There are no files selected for viewing
-
jaganathanb created this gist
Jul 14, 2016 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,37 @@ /* Function to escape the html with specified whitelist tags & spl chars @param htmlString string string to be escaped @param tags string comma separated tag list to be unescaped @param splChars string comma separated spl char list to be unescaped @example var exTags = 'b,p,strong, i'; var exSplChars = '?,!'; document.querySelector('#editor').innerHTML = safeHTML("<strong> Need</strong> tips? <i> Visit </i> <b> W3Schools! </b>", exTags, exSplChars); */ function safeHTML(htmlString, tags, splChars) { var exDefaults = ' , %', pattern = prepareTagsRegExpPattern() + '|' + prepareCharsRegExpString(); return escape(htmlString).replace(new RegExp(pattern, 'ig'), function(match) { return unescape(match); }); function prepareTagsRegExpPattern() { return (tags || '').split(',').map(function(tag, index, arr) { var text = ''; tag = tag.trim(); if(index === 0) { text = '%3C(' + tag + '|' + '/' + tag; }else if(index === arr.length -1) { text = tag + '|' + '/' + tag + ')%3E'; } else { text = tag + '|' + '/' + tag } return text; }).join('|'); } function prepareCharsRegExpString() { return (splChars || '').split(',').map(function(char) { return escape(char); }).join('|') + '|' + (exDefaults || '').split(',').map(function(char) { return escape(char) }).join('|') ; } }