Reputation: 10502
Here is the code I am using to escape html tags:
var ne = document.createElement('textarea');
ne.appendChild(document.createTextNode(str));
return ne.innerHTML;
I do not want to escape <strong></strong> <i></i>
tags
e.g <h1>sasasas<strong>hello</strong></h1>
should be <h1>sasasas<strong>hello</strong></h1>
how can i do that?
Upvotes: 0
Views: 212
Reputation: 16214
var ne = document.createElement('textarea'),
str = '<h1>sasasas<strong>hello</strong></h1>';
var newstr = str.replace(/(<\/?(\w+)>)/g, function(m0, m1, m2) {
if (m2 != 'strong' && m2 != 'i')
return m0.replace(/</g, '<')
.replace(/>/g, '>');
else
return m0;
});
ne.appendChild(document.createTextNode(newstr));
return ne.innerHTML;
It works for the simple tags (without attributes - I do not know the source of your text). Or, as it was said in comments, something like this:
var ne = document.createElement('textarea'),
str = '<h1>sasasas<strong>hello</strong></h1>';
var newstr = str.replace(/(<(\/?(strong|i))>)/gi, 'BRA$2KET')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/(BRA(\/?(strong|i))KET)/gi, '<$2>');
ne.appendChild(document.createTextNode(newstr));
return ne.innerHTML;
or, the best way, just restore the escaped tags
var ne = document.createElement('textarea'),
str = '<h1>sasasas<strong>hello</strong></h1>';
var newstr = str.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/(<(\/?(strong|i))>)/gi, '<$2>');
ne.appendChild(document.createTextNode(newstr));
return ne.innerHTML;
Upvotes: 1