如何从字符串中删除所有HTML标签

11

嗨,我正在尝试从特定字符串中删除所有HTML标签,但出现错误。

这是我的字符串:

<p>Hi there</p> ~ wifi free <p>this is test</p> ~ breakfast free <p>This is another test</p>

以下是我的jQuery代码:

var item = <p>Hi there</p> ~ wifi free <p>this is test</p> ~ breakfast free <p>This is another test</p>;
item = item.replace(/~/g, '');
item = item.replace(/<p>/g, '');
item = item.replace('</p>'/g, '');
var splitArray = item.split('<br />');
var l = splitArray.length;
for (var i = 0; i < l; i++) {
    out = out + "<li><span class='sp_icon sp_star_icon'></span> "
          + splitArray[i].trim() + "</li>";
}
console.log(item);

2
错误是否指的是你的第一个字符串没有用引号括起来?或者这不是你代码中实际的样子?请确保你发布的内容与你正在使用的完全一致。并告诉我们错误信息。 - Brian Warshaw
你的变量 item 必须用引号括起来。 - Bhushan Kawadkar
第三个替换 ('</p>'/g) 看起来很奇怪。我认为那根本行不通。 - Alvaro Montoro
8个回答

46

2
OP应该注意:这并不推荐,因为您的正则表达式永远无法像真正的浏览器HTML解析引擎那样宽松和全面。如果您正在删除已知的HTML,则可以使用,但如果此HTML未知,则应该真正寻求适当的HTML解析引擎,最方便的是原生浏览器DOM :) - James

9

不要自己动手,让DOM来帮你。

例如(使用jQuery)

jQuery("<p>Hi there</p>...").text();
    // => "Hi there..."

例如(不使用jQuery)
var d = document.createElement('div');
d.innerHTML = "<p>Hi there</p>...";
(d.textContent || d.innerText); // => "Hi there..."

6
你可以使用原生JS来实现这个功能。

var item = '<p>Hi there</p> ~ wifi free <p>this is test</p> ~ breakfast free <p>This is another test</p>';

function getText(html) {
    var tmp = document.createElement('div');
    tmp.innerHTML = html;
    
    return tmp.textContent || tmp.innerText;
}

console.log(getText(item));


4
var item = '<p>Hi there</p> ~ wifi free <p>this is test</p> ~ breakfast free <p>This is another test</p>'

item = item.replace(/<\/?.+?>/ig, '');

3
今日免费次数已满, 请开通会员/明日再来
filtered = yourString.replace(/<[a-z]{1}>.*?<\/[a-z]{1}>/gi, ""); 

如果您只想去掉

标记并保留其中的文本,则可以这样做:
filtered = yourString.replace(/<\/{0,1}[a-z]+>/gi, "");

1
你可以使用 jQuery 的 text 方法。
var item = '<p>Hi there</p> ~ wifi free <p>this is test</p> ~ breakfast free <p>This is another test</p>';
console.log($(item).text());

你可以在 http://jsfiddle.net/gL7fufax/ 查看代码。

0
根据您的要求(删除<p>元素),以下是相应的字符串:
item = item.replace(/<\/?p>/g,''); // will globally find “<p>” and “</p>” only

0
你可以将字符串包装在 jQuery 对象中:
var removeElements = function(text, selector) {
    var wrapped = $("<div>" + text + "</div>");
    wrapped.find(selector).remove();
    return wrapped.html();
}

var removedPString = removeElements("<p>Hi there</p> ~ wifi free <p>this is test</p> ~ breakfast free <p>This is another test</p>", "p");

这样做不行,因为它不仅会删除标签,还会删除标签内的文本。 - Alvaro Montoro
我使用过这个,它有效。 - NaveenG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接