How to remove HTML Tags from a string in Javascript

Posted by admin 10 November, 2008

Some days back, one of my team members came to me saying he need a function which is capable of remove the html tags using javascript. I mean if we pass “ this is demo ” this string to the function. It supposes to return only “This is demo” and the main thing is with having no formatting at all, Just the simple text between tags.
So, Initially I make it happen using regular expression but the strategy fails when some think like   comes in. after snatching my hairs, putting some hard hand on the keyboard just before the moment I go for suicide J the following code did the trick.

function removeHTMLTags(htmlString){
if(htmlString){
var mydiv = document.createElement(”div”);
mydiv.innerHTML = htmlString;

if (document.all) // IE Stuff
{
return mydiv.innerText;

}
else // Mozilla does not work with innerText
{
return mydiv.textContent;
}
}
}

Let's Share:
  • Live
  • Digg
  • del.icio.us
  • StumbleUpon
  • Facebook
  • Google
  • LinkedIn
  • Webride
  • E-mail this story to a friend!
  • MySpace
  • TwitThis
Categories : Javascript Tags : ,

Comments
November 10, 2008

thanks usman,very valuable

Posted by Syed Safiullah Hussaini
November 10, 2008

wow what a wonderful way you described it really helps me alot thanks mr agha usman keep doing this sort work for helping more pplz :)

Posted by yasir
January 15, 2009

It helped me alot. Thank you very much, Agha Usman.

Posted by Cloudless
April 16, 2009

Wow! Such a cool way to remove tags! As far as I can see, even the code that’s enclosed in script tags doesn’t evaluate this way.

Amazing, thanks!

Posted by Igor
June 25, 2009

this is really cool script thanks really works well

Posted by kABHIr
Leave a comment

(required)

(required)