Manish Kumar
Manish Kumar

Reputation: 10502

Escape html tags except few given tags

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 &lt;h1&gt;sasasas<strong>hello</strong>&lt;/h1&gt;

how can i do that?

Upvotes: 0

Views: 212

Answers (1)

Cheery
Cheery

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, '&lt;')
               .replace(/>/g, '&gt;');
  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, '&lt;')
                .replace(/>/g, '&gt;')
                .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, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/(&lt;(\/?(strong|i))&gt;)/gi, '<$2>');
ne.appendChild(document.createTextNode(newstr));
return ne.innerHTML;

Upvotes: 1

Related Questions