如何从字符串中删除所有html标记

Sur*_*ttu 2 javascript jquery

嗨,我试图从显示错误的特定字符串中删除所有html标记.

这是我的字符串:

<p>Hi there</p> ~ wifi free <p>this is test</p> ~ breakfast free <p>This is another test</p>
Run Code Online (Sandbox Code Playgroud)

我的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);
Run Code Online (Sandbox Code Playgroud)

ple*_*xus 20

你可以用正则表达式删除所有的html标签:/<(.|\n)*?>/g

这里详细描述:http://www.pagecolumn.com/tool/all_about_html_tags.htm

在你的JS代码中,它看起来像这样:

item = item.replace(/<(.|\n)*?>/g, '');
Run Code Online (Sandbox Code Playgroud)

  • OP 应该注意:不建议这样做,因为你的正则表达式永远无法像真正的浏览器 HTML 解析引擎那样宽松和包罗万象。如果您要删除 **已知** HTML,那么这很酷,但如果此 HTML 未知,那么您应该真正寻找合适的 HTML 解析引擎,最方便的是本机浏览器 DOM :) (2认同)

Jam*_*mes 7

不要自己做,让 DOM 为你做。

例如(使用 jQuery)

jQuery("<p>Hi there</p>...").text();
    // => "Hi there..."
Run Code Online (Sandbox Code Playgroud)

例如(没有 jQuery)

var d = document.createElement('div');
d.innerHTML = "<p>Hi there</p>...";
(d.textContent || d.innerText); // => "Hi there..."
Run Code Online (Sandbox Code Playgroud)


Ale*_* T. 5

使用 vanilla 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));
Run Code Online (Sandbox Code Playgroud)