useful actionscript 3 functions

May 16th, 2010 § 14

OK, first post. Lately I've been dabbling with Actionscript so here are two useful functions and I will update the post with more.

First one is an as3 utf8 encode function. This was found at Destroy Today

public static function encodeUTF8 (text:String):String {
	var a:uint, n:uint, A:uint;
	var utf:String;
	utf = "";
	A = text.length;

	for (a = 0; a < A; a++) {
		n = text.charCodeAt (a);
		if (n < 128) {
			utf += String.fromCharCode (n);
		} else if ((n > 127) && (n < 2048)) {
			utf += String.fromCharCode ((n >> 6) | 192);
			utf += String.fromCharCode ((n & 63) | 128);
		} else {
			utf += String.fromCharCode ((n >> 12) | 224);
			utf += String.fromCharCode (((n >> 6) & 63) | 128);
			utf += String.fromCharCode ((n & 63) | 128);
		}
	}
	return utf;
}

Second is an Actionscript implementation of PHP’s html_strip_tags from Flexer

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;
}

An AS3 regular expression to check for email validity:

public static function validateEmail(email:String):Boolean {
    var emailExpression:RegExp = /^[a-z][\w.-][email protected]\w[\w.-]+\.[\w.-]*[a-z][a-z]$/i;
    return emailExpression.test(email);
}

Tagged:

§ 14 Responses to “useful actionscript 3 functions”

What's this?

You are currently reading useful actionscript 3 functions at Discorganized.

meta

Partly powered by CleverPlugins.com