且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-02 21:08:22

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

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
});

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

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).