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

moe*_*oey 10 html javascript jquery

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

var s = "<p>Hello World!</p><p>By Mars</p>";
Run Code Online (Sandbox Code Playgroud)

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

Tim*_*ora 9

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

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

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

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

如果你正在分析大量的HTML(例如,解释一个屏幕抓取的结果),使用服务器端的HTML解析库,不是jQuery的(吨帖子在这里大约HTML解析).