javascript 使用 jQuery 从字符串中删除 HTML 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8692423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:14:18  来源:igfitidea点击:

Remove HTML Tags From A String, Using jQuery

javascriptjqueryhtml

提问by moey

I have a simple string e.g.

我有一个简单的字符串,例如

var s = "<p>Hello World!</p><p>By Mars</p>";

How do I convert sto a jQuery object? My objective is to remove the <p>s and </p>s. I could have done this using regex, but that's rather not recommended.

如何转换s为 jQuery 对象?我的目标是删除<p>s 和</p>s。我本可以使用正则表达式完成此操作,但不推荐这样做

采纳答案by Tim Medora

In the simplest form (if I am understanding correctly):

以最简单的形式(如果我理解正确的话):

var s = "<p>Hello World!</p><p>By Mars</p>";
var o = $(s);
var text = o.text();

Or you could use a conditional selector with a search context:

或者您可以使用带有搜索上下文的条件选择器:

// load string as object, wrapped in an outer container to use for search context
var o = $("<div><p>Hello World!</p><p>By Mars</p></div>");

// sets the context to only look within o; otherwise, this will return all P tags
var tags = $("P", o); 

tags.each(function(){
    var tag = $(this); // get a jQuery object for the tag
    // do something with the contents of the tag
});

If you are parsing large amounts of HTML (for example, interpreting the results of a screen scrape), use a server-side HTML parsing library, not jQuery (tons of posts on here about HTML parsing).

如果您要解析大量 HTML(例如,解释屏幕抓取的结果),请使用服务器端 HTML 解析库,而不是 jQuery(这里有大量关于 HTML 解析的帖子)。

回答by Shiplu Mokaddim

To get all the strings there use

要获取那里的所有字符串,请使用

var s = "<p>Hello World!</p><p>By Mars</p>";
var result = "";
$.each($(s), function(i){
    result += " " + $(this).html();
});

回答by Mr. BeatMasta

if you don't want regex, why don't u just:

如果你不想要正则表达式,你为什么不:

var s = "<p>Hello World!</p><p>By Mars</p>";
s = s.replace('<p>', '').replace('</p>', '');