Lately I’ve been working with Rich Text Editor so I found that I need more than what RTE offers. Recently I needed a function to strip HTML tags. If you have a PHP background you can remember the strip_tags function from PHP4 and PHP5 where you could strip all HTML tags but the ones you specified as allowable tags.
My function receives two string parameters:
- html: the string with the HTML
- tags: a string with allowable tags separated by comma
In a few words I’ll explain what it does step by step:
- split the allowable tags string by any kind of comma separation
- remove empty tags or spaces
- search for tags in the HTML string
- if found add it to “to be removed array”
- remove the tags from HTML string
public static function stripHtmlTags(html:String, tags:String = ""):String { var tagsToBeKept:Array = new Array(); if (tags.length > 0) tagsToBeKept = tags.split(new RegExp("\\s*,\\s*")); var tagsToKeep:Array = new Array(); for (var i:int = 0; i < tagsToBeKept.length; i++) { if (tagsToBeKept[i] != null && tagsToBeKept[i] != "") tagsToKeep.push(tagsToBeKept[i]); } var toBeRemoved:Array = new Array(); var tagRegExp:RegExp = new RegExp("<([^>\\s]+)(\\s[^>]+)*>", "g"); var foundedStrings:Array = html.match(tagRegExp); for (i = 0; i < foundedStrings.length; i++) { var tagFlag:Boolean = false; if (tagsToKeep != null) { for (var j:int = 0; j < tagsToKeep.length; j++) { var tmpRegExp:RegExp = new RegExp("<\/?" + tagsToKeep[j] + "[^<>]*?>", "i"); var tmpStr:String = foundedStrings[i] as String; if (tmpStr.search(tmpRegExp) != -1) tagFlag = true; } } if (!tagFlag) toBeRemoved.push(foundedStrings[i]); } for (i = 0; i < toBeRemoved.length; i++) { var tmpRE:RegExp = new RegExp("([\+\*\$\/])","g"); var tmpRemRE:RegExp = new RegExp((toBeRemoved[i] as String).replace(tmpRE, "\\$1"),"g"); html = html.replace(tmpRemRE, ""); } return html; }
Tags: ActionScript, HTML, Rich Text Editor, RTE
This post was written by Andrei Ionescu
Views: 3328



















thanks a lot : )
Small oversight:
This code won’t work as is without the second parameter.
If the second paramter is null, it will crash on the 2nd line where you check “tags.length”. Easy fix is to make the 2nd parameter default to an empty string (”"), which will have a valid length.
Thanks JohnG! I’ve modified the code also.