Javascript Remove HTML Tags

I found a handy Javascript function by Robert Nyman where you can remove HTML TAGS of of a text. It works well in both IE and Mozilla browsers so no problem for the user to worry about cross-browser issues. Thank you Robert, this saves us a bundle of time creating our own functions for this sort of need.

function removeHTMLTags(text) {
	var strInputCode = text;
	/*
	This line is optional, it replaces escaped brackets with real ones,
	i.e. < is replaced with < and > is replaced with >
	*/
	strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1) {
		return (p1 == “lt”)?<:>;
	});
 
	var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, “”);
	//alert(”Output text:\n” + strTagStrippedText);
	// Use the alert below if you want to show the input and the output text
	// alert(”Input code:\n” + strInputCode + “\n\nOutput text:\n” + strTagStrippedText);
	return strTagStrippedText;
}

Donations appreciated. Every little $ helps. Or click Google +1.

Related Posts Plugin for WordPress, Blogger...
  1. 2 Responses to “Javascript Remove HTML Tags”

  2. Doesn’t work with this: “>alert(1)<

    By Igor on Oct 26, 2012

  3. @igor: okay, this is an old post that i dont have time to verify again. if you do get to solve the bug, please share it. thank you

    By admin on Oct 26, 2012

Post a Comment