为什么使用替换来取消转义 html 标签也会去除所有其他 html 标签

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

本文关键字:标签 html 其他 替换 取消 转义 为什么      更新时间:2023-09-26

我需要将表中的&lt;&gt;转换为<>。我用来执行此操作的功能运行良好。

<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>

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

但是,此函数还会删除不需要任何转义的<em>标记。有人知道为什么吗?

https://jsfiddle.net/et1crLug/

因为你用.text()来获取你的HTML内容。

请改用.html()

var t = $this.html();

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

使用 html(function) 替换each循环的快捷方式方法

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

演示

当你使用 replace() 时,我发现它只替换了第一个实例。如果您使用正则表达式,则可以将其设置为将&lt;的每个实例替换为&gt; /g

https://jsfiddle.net/xdoj0qLy/