从HTML删除烦人的双引号

时间:2018-10-05 04:52:37

标签: javascript jquery html css regex

当我将json转换为html友好时,我从json中得到令人讨厌的双引号。

可以在下面的代码中看到<p>"的开始和"<\p>的结尾。如何删除它们。尝试以下操作无效。

$("p").html().replace(/['"]+/g, '')

这是js变量内部的动态html。

<p>"<!--HTML icon appears here--><a href="https://www.example.com/viewer/event.jsp?ei=1434586&amp;tp_key=e8ced8705c" target="_blank">Click here for web</a><br>
<!--PDF icon appears here--><a href="../file/408427349/Index?KeyFile=1500113055" target="_blank">Press Release</a><br>
<!--PDF icon appears here--><a href="../file/4234/Index?KeyFile=234324" target="_blank">somelink</a><br>"</p>

2 个答案:

答案 0 :(得分:1)

您是否忘了在清理文本后设置html?

这应该做到:

var text = $('p').html().replace(/['"]+/g, '')
$('p').html(text)

// or you can just:
// $('p').html($('p').html().replace(/['"]+/g, ''))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>"<!--HTML icon appears here--><a href="https://event.web.com/viewer/event.jsp?ei=1434586&amp;tp_key=e8ced8705c" target="_blank">Click here for web</a><br>
<!--PDF icon appears here--><a href="../file/408427349/Index?KeyFile=1500113055" target="_blank">Press Release</a><br>
<!--PDF icon appears here--><a href="../file/4234/Index?KeyFile=234324" target="_blank">somelink</a><br>"</p>

答案 1 :(得分:1)

您可以使用Element.outerHTML属性删除任何'"的引号。

/[><]['"]+[><]/g将删除开头和结尾标记之间的多余引号。不会删除attribute = value对中的引号。

let p = document.querySelector('p');

p.outerHTML = p.outerHTML.replace(/[><]['"]+[><]/g, '');
<p>"<!--HTML icon appears here--><a href="https://event.web.com/viewer/event.jsp?ei=1434586&amp;tp_key=e8ced8705c" target="_blank">Click here for web</a><br>
<!--PDF icon appears here--><a href="../file/408427349/Index?KeyFile=1500113055" target="_blank">Press Release</a><br>
<!--PDF icon appears here--><a href="../file/4234/Index?KeyFile=234324" target="_blank">somelink</a><br>"</p>