我有这段代码 :
var content = "<p>Dear sms,</p><p>This is a test notification for push message from center II.</p>";
and 我想从上述字符串中删除所有的 <p>
和 </p>
标签。只想显示没有 HTML 标签的字符串值,例如:"Dear sms, This is a test notification for push message from center II."
我有这段代码 :
var content = "<p>Dear sms,</p><p>This is a test notification for push message from center II.</p>";
and 我想从上述字符串中删除所有的 <p>
和 </p>
标签。只想显示没有 HTML 标签的字符串值,例如:"Dear sms, This is a test notification for push message from center II."
为什么不让jQuery来做呢?
var content = "<p>Dear sms,</p><p>This is a test notification for push message from center II.</p>";
var text = $(content).text();
content
中有类似于<div>的内容,那么在运行此代码后,它将变成一个标签。 - cdmckay<br/>
。 - Fabian S.这是我的解决方案,
function removeTags(){
var txt = document.getElementById('myString').value;
var rex = /(<([^>]+)>)/ig;
alert(txt.replace(rex , ""));
}
content = content.replace(/(<p>|<\/p>)/g, "");
<p class="bla"></p >
- Oscar Broman/(<p[^>]*>|<\/p>)/g
。 - HBPvar $string = '<a href="link">aaa</a>';
var $string2 = '<a href="link">aaa</a>';
var $string3 = 'BBBBB';
var $string4 = 'partial<script';
var $string5 = 'has spaces';
function StripTags(string) {
var decoded_string = $("<div/>").html(string).text();
return $("<div/>").html(decoded_string).text();
}
console.log(StripTags($string));
console.log(StripTags($string2));
console.log(StripTags($string3));
console.log(StripTags($string4));
console.log(StripTags($string5));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
var content = "a<br />";
var withoutP = $(content).text()
alert(withoutP )
这个无法使用 .text() 解决方案。
在标记中放置隐藏元素
,或者使用jQuery创建它。使用此代码获取纯文本,而不会出现不完整标签的复杂情况,例如<
等。
content = $(hiddenElement).html($(hiddenElement).html(content).text()).text();