moey
moey

Reputation: 10887

Remove HTML Tags From A String, Using jQuery

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.

Upvotes: 11

Views: 13373

Answers (3)

Tim M.
Tim M.

Reputation: 54359

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

Upvotes: 10

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57640

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

Upvotes: 1

Mr. BeatMasta
Mr. BeatMasta

Reputation: 1312

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

Upvotes: 0

Related Questions