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

时间:2022-08-27 17:12:54

I have a simple string e.g.

我有一个简单的字符串。

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

How do I convert s to 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对象?我的目标是去除

s和

s。我本可以使用regex来实现这一点,但并不推荐这样做。

3 个解决方案

#1


9  

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解析的文章)。

#2


1  

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

#3


0  

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

如果你不想要regex,为什么不:

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

#1


9  

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解析的文章)。

#2


1  

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

#3


0  

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

如果你不想要regex,为什么不:

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