Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 566
moey Avatar asked Jan 01 '12 08:01

moey


People also ask

How to remove HTML tags from string in jQuery?

log($('#dvTest'). text()); You can also strip/remove HTML tags from any variable as well as text() is jQuery function, so the variable needs to be converted into a jQuery object so that text() can be used. var str = '<div>Sample <u>HTML</u> <b>Text</b> with <i>tags</i></div>'; console.

How to remove HTML tags from string in JavaScript?

To strip out all the HTML tags from a string there are lots of procedures in JavaScript. In order to strip out tags we can use replace() function and can also use . textContent property, . innerText property from HTML DOM.

How do I remove a tag from a string?

The HTML tags can be removed from a given string by using replaceAll() method of String class. We can remove the HTML tags from a given string by using a regular expression. After removing the HTML tags from a string, it will return a string as normal text.


2 Answers

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();
});
like image 26
Shiplu Mokaddim Avatar answered Oct 19 '22 23:10

Shiplu Mokaddim


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

like image 56
Tim M. Avatar answered Oct 19 '22 23:10

Tim M.