Reputation: 5126
I have a following string array
["div", "span", "h1", "h2", "h3", "h4", "h5", "p", "br", "a", "strong", "em", "li", "ul", "ol", "b", "i", "u", "hr", "font", "pre", "q", "s", "strike", "blockquote", "sub", "sup"]
I have a string text which also contains HTML tags, I need to verify that the html tags in the paragraph text are out of those defined in string array above. Apart from these if any tags are present error has to be thrown. I saw many methods but couldn't find any simple javascript implementation of these.
Upvotes: 3
Views: 110
Reputation: 78525
You would need to parse the HTML, then test all the tags to see if they are matched in the array. I would just parse the HTML, walk through the DOM nodes and test each tagname against the array:
var allowedTags = ["div", "span", "h1", "h2", "h3", "h4", "h5", "p", "br", "a", "strong", "em", "li", "ul", "ol", "b", "i", "u", "hr", "font", "pre", "q", "s", "strike", "blockquote", "sub", "sup"];
var wrapper = document.createElement("div");
wrapper.innerHTML = "<h1>Your HTML here</h1><p>Test</p><span><audio /></span>";
function walk(element) {
var el = element;
var len = el.childNodes.length, i;
for(i = 0; i<len; i++) {
if(!walk(el.childNodes[i])) return false;
}
return !(el.tagName && allowedTags.indexOf(el.tagName.toLowerCase()) === -1);
}
var result = !walk(wrapper);
console.log("Contains invalid tags: " + result);
Upvotes: 1
Reputation: 17605
You would have to parse the tags out of the string and then check the tag names against the array; this is discussed in this question. The way of parsing the string depends on your environment, but the topic is discussedin this question.
Upvotes: 0