5

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"

6

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your answer.this solution not work on a<div>b</div><div>c</div><div>d</div><div>
1

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/

1 Comment

This causes the same result like "thisismytextsample "
1

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

1 Comment

thanks for your answer.this solution not work on a<div>b</div><div>c</div><div>d</div><div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.