• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 8899
  • Last Modified:

htmldecode function in javascript

I need an HTMLDecode function in javascript..

I read a data in Javascript as document.getElementById("test").innerHTML;

If i need to remove any html data while reading how do I do that..for e.g. the data may contain   etc

how do parse any data or decode the data. in javascript
0
intikhabk
Asked:
intikhabk
  • 3
  • 2
1 Solution
 
hieloCommented:
try:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd"> 
<html>
<head>
<title></title>
<style type="text/css">
<!--
.x{color:blue;}
-->
</style>
<script type="text/javascript">
function decodeHTML(e){
	var clean = document.getElementById(e).innerHTML.replace(/<[^>]*>/g,"");
	alert( clean );
return clean;
}
</script>
</head>
<body>
<div id="elem1" onclick="decodeHTML(this.id)">
	<span class="x">Hello</span> <strong>world</strong>
</div>
</body>
</html>

Open in new window

0
 
intikhabkAuthor Commented:
but if the text is Hello World&nbsp;
it does not work properly...
for eg: if it is
<div id="elem1" onclick="decodeHTML(this.id)">
      Hello World&nbsp;
</div>

the alert returns Hello World&nbsp;
0
 
hieloCommented:
>>but if the text is Hello World&nbsp
Better yet, what if it is:
Procter & Gamble

have you tried a single ampersand?
0
 
intikhabkAuthor Commented:
so how do i remove special characters also
0
 
hieloCommented:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd"> 
<html>
<head>
<title></title>
<style type="text/css">
<!--
.x{color:blue;}
-->
</style>
<script type="text/javascript">
//you will need a "replacement table" so that the script below can make the proper
//replacements you wish
var entities=[
			['&amp;','&'],
			['&nbsp;',' ']
		];
function decodeHTML(e){
	var clean = document.getElementById(e).innerHTML.replace(/<[^>]*>/g,"");
	for( var i=0, limit=entities.length; i < limit; ++i)
	{
		clean = clean.replace( new RegExp(entities[i][0],"ig"), entities[i][1]);
	}
	alert( clean );
return clean;
}
</script>
</head>
<body>
<div id="elem1" onclick="decodeHTML(this.id)">
	<span class="x">Hello</span> &nbsp; <strong> & world</strong>
</div>
</body>
</html>

Open in new window

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now