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.
-
-
-
-
-
-
-
-
-
-
- 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('|') ;
- }
-
- }
Here is more
details