javascript - Remove HTML Tags From A String, Using jQuery - Stack Overflow

I have a simple string e.g.var s = "<p>Hello World!<p><p>By Mars<p>"

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.

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.

Share Improve this question edited May 23, 2017 at 12:29 CommunityBot 11 silver badge asked Jan 1, 2012 at 8:38 moeymoey 10.9k25 gold badges73 silver badges112 bronze badges 2
  • 2 You just should have read the documentation a bit better: api.jquery.com/jQuery/#jQuery2 – Felix Kling Commented Jan 1, 2012 at 9:09
  • @hippietrail: The latter. The accepted answer i.e. .text() does fulfill what I needed. – moey Commented Oct 19, 2012 at 14:04
Add a comment  | 

3 Answers 3

Reset to default 10

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

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

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>', '');

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1739485735a4129512.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信