views:

682

answers:

3

Hi, 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"

Thx

+2  A: 

No, that is not possible using regex. You can only replace A with a, B with b, etc. Not all at once.

Why not simply use toLowerCase()?

Bart Kiers
I want to replace html tags, and those are in upper case, but XHTML allows only lowercase tags, therefore I need them in lowercase
luccio
A: 

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

viatropos
Thx, I'll give it a try, but it looks promising :)
luccio
A: 
var html = '<HTML><HEAD><BODY>TEST</BODY></HEAD></HTML>';
var regex = /<([^>]*)>/g;
html = html.replace(regex, function(x) { return x.toLowerCase() });
alert(html);
ketki