AlfieWebDevTips Homefor new and experienced developers
[Home Home] [Web Development Web Development ] [Code Generators Code Generators ] [Resources Resources ] [Contact Us Contact ] |WebDevTips Privacy Privacy |
Print This Page

You are here : Home - Web Development - Javascript - Strip HTML from a javascript string

Strip HTML from a javascript string


Why would you want to do this? Well in normal circumstances you probably wouldn't need to but I recently had to do it for a script I wrote.

Briefly, I had written a script that formatted help hints in a floating layer, the problem I had was that, if a browser didn't support the methods used they never got the help tip. The tips were written into a javascript array and contained html tags, so I decided that if the code wasn't supported then the users would get the help hint as an alert.

Let's say the string for our floating layer looked like this
var helphint = "<p> I am a paragraph of text with some <strong>BOLD</strong> text</p>";
See how it looked in an alert - notice the html tags.

So what we do is strip the html tags from the string using a regular expression. See how it looks now.

Here's the example code used on this page


<script language="JavaScript"> 
<!-- 
var helphint = "<p>I am a paragraph of text with some <strong>BOLD</strong> text</p>"; 
function showhint(){ 
alert(helphint); 

 
function showhint2(){ 
var re= /<\S[^>]*>
/g; 
helphint = helphint.replace(re,""); 
alert(helphint); 

// --> 
</script>

Use our Regular Expression Tester to create your own regular expression.s




Why not discuss this article in our forum?
02-Feb-2004 - updated (13-Sep-07)




Google
 

[back to top of page]   

[labelled with icra -  - this link will open in a new window] [RSS Content]

[Copyright © WebDevTips]