regex uppercase to lowercase

luccio picture luccio · Mar 27, 2010 · Viewed 33.7k times · Source

Is it possible to transform regexp pattern match to lowercase?

var pattern:RegExp;
var str:String = "HI guys";
pattern = /([A-Z]+)/g;
str = str.replace(pattern, thisShouldBeLowerCase);

Output should look like this: "hi guys"

Answer

Lance Pollard picture Lance Pollard · Mar 28, 2010

You can do something like this, but replace the pattern with exactly what you need:

public static function lowerCase(string:String, pattern:RegExp = null):String
{
    pattern ||= /[A-Z]/g;
    return string.replace(pattern, function x():String
    {
        return (arguments[0] as String).toLowerCase();
    });
}

trace(lowerCase('HI GUYS', /[HI]/g)); // "hi GUYS";

That arguments variable is an internal variable referencing the function parameters. Hope that helps,

Lance