开发者

regex uppercase to lowercase

开发者 https://www.devze.com 2022-12-24 03:31 出处:网络
Is it possible to transform regexp pattern match to lowercase? var patt开发者_运维技巧ern:RegExp;

Is it possible to transform regexp pattern match to lowercase?

var patt开发者_运维技巧ern:RegExp;
var str:String = "HI guys";
pattern = /([A-Z]+)/g;
str = str.replace(pattern, thisShouldBeLowerCase);

Output should look like this: "hi guys"


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


var html = '<HTML><HEAD><BODY>TEST</BODY></HEAD></HTML>';
var regex = /<([^>]*)>/g;
html = html.replace(regex, function(x) { return x.toLowerCase() });
alert(html);


to lowercase

s/[A-Z]/\l&/g

and to uppercase

s/[a-z]/\u&/g


Change all upper english letters to lower in ActionSctipn 3

var pattern:RegExp = /[A-Z]/g;
contentstr = contentstr.replace(pattern,function(a:String,b:int,c:String):String { return a.toLowerCase() } );


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()?


you can use a function as the second argument for string.replace

in your case you could use

var pattern:RegExp;
var str:String = "HI guys";
pattern = /([A-Z]+)/g;
str = str.replace(pattern, function(search, match1) { 
   return match1.toLowerCase() }
);

read more about it here Javascript: how to pass found string.replace value to function?


If you want to convert complete string to lowercase then use .toLowerCase() or .toUpperCase() in javascript.

If you want to replace a particular letter with lowercase in a String then Regex is better.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号