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.
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.
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.
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.
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();
});
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With