Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove html tag from a string using jQquery

I want to remove an HTML tag from string for example remove div,p,br,...

I'm trying to do this:

var mystring = "<div><p>this</p><p>is</p><p>my</p><p>text</p><p>sample</p><p> </p><p> </p></div>"

var html3 = $(mystring).text();

but the result is:

"thisismytextsample  "

How can do it like : "this is my text sample"

like image 763
habiat Avatar asked Aug 12 '14 09:08

habiat


People also ask

How to remove HTML tag from string in jQuery?

Learning jQuery To remove HTML tags, use text() function which returns only the text content and ignores the HTML portion.

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.

How to remove HTML tags from string using 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 to remove elements using jQuery?

Use . remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.


1 Answers

You can get all p tag text in array and then join them with spaces:

$(mystring).find('p').map(function() {
   return $(this).text();
}).toArray().join(' '));

Working Demo

like image 96
Milind Anantwar Avatar answered Oct 04 '22 16:10

Milind Anantwar