habiat
habiat

Reputation: 1434

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"

Upvotes: 5

Views: 910

Answers (3)

amiceli
amiceli

Reputation: 445

You can use replace function :

var mystring="<div><p>this</p><p>is</p><p>my</p><p>text</p></div>"
var stripped = mystring.replace(/(<([^>]+)>)/ig," "); // this is my text

source : http://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/

Upvotes: 1

Sudharsan S
Sudharsan S

Reputation: 15393

Try this using regular expression

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


function RemoveHTMLTags(string1) {
            var regX = /(<([^>]+)>)/ig;
            var html = string1;
            return html.replace(regX, " ");
        }


var res = RemoveHTMLTags(mystring);

alert(res);

DEMO

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

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

Upvotes: 4

Related Questions