简体   繁体   中英

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

eg <h1>sasasas<strong>hello</strong></h1> should be &lt;h1&gt;sasasas<strong>hello</strong>&lt;/h1&gt;

how can i do that?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM