Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Stripping out HTML (except <p> and )

Status
Not open for further replies.

iaresean

Programmer
Mar 24, 2003
570
ZA
Hi all;

I want to strip out all the html from a textarea, but I want to leave the <p> and <br> tags. Thereafter I would like to strip any styles that may be defined within the leftover <p> and <br> tags.

This is the javascript regex I have so far to match all tags:
/<\/?[a-z][a-z0-9]*[^<>]*>/

I found it in a regex library. Does anyone know how I can modify this to not match <br> or <p> tags, taking into consideration that they may have styling defined?

Thank you for any and all help!

Sean. [peace]
 
Hi all;

I managed to do it myself, code below. I fetch the html contained within the textarea called ct13_freeTextBox and then strip it of any html, and replacing styled p and br tags with unstyled ones.

Code:
<script type="text/javascript">
    function cleanHtml() {
        var strText = document.getElementById('ctl3_freeTextBox').value;
                                                
        // Replace the p tags
        strText = strText.replace(/<p *[^<>]*>/gi, "###P_START###");
        strText = strText.replace(/<\/p *[^<>]*>/gi, "###P_END###");
        
        // Replace the br tags
        strText = strText.replace(/<br *[^<>]*>/gi, "###BR###");
        
        // Replace all html tags
        strText = strText.replace(/<\/?[a-z][a-z0-9]*[^<>]*>/gi, "");
        
        // Restore the p tags
        strText = strText.replace(/###P_START###/gi, "<p>");
        strText = strText.replace(/###P_END###/gi, "</p>");
                                                
        // Restore the br tags
        strText = strText.replace(/###BR###/gi, "<br />");
        
        //alert(strText);
        document.getElementById('ctl3_freeTextBox').value = strText;
    }                 
    
</script>

Hope this helps!

Sean. [peace]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top