[英]How do I replace “<br /><br />” with “<br />” in HTML using JavaScript and jQuery?
我有一个验证摘要,有时在末尾有多个br
标签,如下所示:
<div id="ValidationSummary1" class="alert alert-error">
Last 4-digits of Social Security number does not match
the Member record on file for the Member ID number you
have entered.<br />
Date of Birth does not match the Member record on file for the Member ID
number you have entered.<br /><br />
</div>
我试图在任何时候都找到两个背对背的br
标签,并将其替换为如下所示的一个:
$('#ValidationSummary1').replace('<br /><br />', '<br />');
我知道没有replace()
函数。 像这样简单的事情有什么替代方案?
使用.html()
获取并设置通过标准JS replace()
传递的内容。
var div = $('#ValidationSummary1');
div.html(div.html().replace('<br /><br />', '<br />'));
JavaScript本身确实具有replace
功能,并且鉴于jQuery是基于 JavaScript构建的框架,因此您确实可以使用该方法。 因此,这意味着您必须执行一个get-manipulate-set过程,而不是执行一些不错的jQuery方法链接。
var $val= $('#ValidationSummary1');
$val.html($val.html().replace(/[<br>]+$/, '<br/>');
无论多少
他们将被替换为一个
(更好的html)
在您的情况下(需要删除html标签),最好的解决方案是使用.text()
而不是.html()
。 区别在于.html()
保留html标签,而.text()
仅保留文本(删除任何html)。
例如:
var value1 = $('.some_div').html(); //returns text content with HTML tags
var value2 = $('.some_div').text(); //returns only text content
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.