最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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>', '');
发布评论

评论列表(0)

  1. 暂无评论