简体   繁体   English

为什么使用replace对unescape html标签进行脱模也可以去除所有其他html标签?

[英]Why does using replace to unescape html tags strips out all other html tags as well?

I need to convert &lt; 我需要转换&lt; and &gt; &gt; in a table to < and > . <>的表中。 The function I'm using to do this works well. 我用于执行此操作的功能效果很好。

<div class="schedule">    
<table>
      <tbody>
        <tr>
          <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.&lt;br /&gt;
            <em>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</em>&lt;br /&gt;Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</td>
        </tr>
      </tbody>
    </table>
</div>

and

$('.table-container td').each(function(){
  var $this = $(this);
  var t = $this.text();
  $this.html(t.replace('&lt','<').replace('&gt', '>'));
});

However, this function also removes the <em> tags that don't need any unescaping. 但是,此函数还会删除不需要任何转义的<em>标记。 Anyone know why? 有人知道为什么吗?

https://jsfiddle.net/et1crLug/ https://jsfiddle.net/et1crLug/

Because you used .text() to get your HTML content. 因为您使用.text()来获取HTML内容。

Use .html() instead: 使用.html()代替:

var t = $this.html();

https://jsfiddle.net/et1crLug/1/ https://jsfiddle.net/et1crLug/1/

Shortcut method using html(function) to replace the each loop 使用html(function)替换each循环的快捷方式

$('.table-container td').html(function(_,existing){
     return existing.replace('&lt;','<').replace('&gt;', '>');
});

DEMO 演示

When you're using replace() i've found it only replaces the first instance. 当您使用replace()时,我发现它仅替换第一个实例。 If you use regex you can set it to replace every instance of &lt; 如果使用正则表达式,则可以将其设置为替换&lt;每个实例&lt; and &gt; &gt; with /g /g

https://jsfiddle.net/xdoj0qLy/ https://jsfiddle.net/xdoj0qLy/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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