Created
July 2, 2015 14:49
-
-
Save asabaylus/53378907a336cbbbce8b to your computer and use it in GitHub Desktop.
Scrub HTML from input
This file contains 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
'use strict'; | |
var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*', | |
tagOrComment = new RegExp( | |
'<(?:' + | |
// Comment body. | |
'!--(?:(?:-*[^->])*--+|-?)' + | |
// Special "raw text" elements whose content should be elided. | |
'|script\\b' + tagBody + '>[\\s\\S]*?</script\\s*' + | |
'|style\\b' + tagBody + '>[\\s\\S]*?</style\\s*' + | |
// Regular name | |
'|/?[a-z]' + | |
tagBody + | |
')>', 'gi' | |
); | |
function decodeText(str) { | |
var txt = document.createElement('textarea'); | |
txt.innerHTML = str; | |
return txt.value; | |
} | |
function sanitize(str) { | |
var oldStr; | |
do { | |
oldStr = str; | |
str = decodeText(str); | |
str = str.replace(tagOrComment, ''); | |
} while (str !== oldStr); | |
return str.replace(/</g, '<'); | |
} | |
module.exports = sanitize; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment