[英]Why does using replace to unescape html tags strips out all other html tags as well?
I need to convert <
我需要转换
<
and >
和
>
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.<br />
<em>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</em><br />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('<','<').replace('>', '>'));
});
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('<','<').replace('>', '>');
});
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
<
如果使用正则表达式,则可以将其设置为替换
<
每个实例<
and >
和
>
with /g
/g
https://jsfiddle.net/xdoj0qLy/ https://jsfiddle.net/xdoj0qLy/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.