yarek
yarek

Reputation: 12064

as3 replaceAll insensitive

I have this as3 function

public static function StringReplaceAll( source:String, find:String, replacement:String ) : String {
      return source.split( find ).join( replacement );
}

Works fine: any idea how to make it case insenstive ? Regards

Upvotes: 4

Views: 7961

Answers (2)

Humble Hedgehog
Humble Hedgehog

Reputation: 2065

A quick way could be to do two replacements. One for the lowerCase and one for the upperCase. It'll look something like this:

public static function StringReplaceAll( source:String, find:String, replacement:String ) : String 
{

    var replacedLowerCase:String = StringReplace(source, find.toLowerCase(), replacement.toLowerCase());

    return StringReplace(replacedLowerCase, find.toUpperCase(), replacement.toUpperCase());
}

private static function StringReplace( source:String, find:String, replacement:String ) : String 
{
    return source.split(find).join(replacement);
}

So in this case you'll keep the case of your find intact i.e.:

trace(StringReplaceAll('HELLO there', 'e', 'a'));
// traces HALLO thara

If you don't want to keep the case intact @RIAstar's String.replace() answer is cleaner. (But you could of course also use his example twice for that matter)

Upvotes: -1

RIAstar
RIAstar

Reputation: 11912

Just use the String#replace() function.

for example:

trace("HELLO there".replace(/e/gi, "a"));
//traces HaLLO thara

The first argument in the replace function is a regular expression. You'll find information about them all over the web. And there's this handy tool from Grant Skinner called Regexr with which you can test your regular expressions ActionScript style.

The part between the two forward slashes (/) is the actual regex.

  • The 'g' after the regex means "replace globally" (i.e. all occurrences of the letter 'e' in the example, without the 'g' it would just replace the first occurrence).
  • The 'i' means "do a case insensitive search" (in the example, without the 'i' the capital E wouldn't have been replaced).

Note that /e/gi is actually just a shorthand for new RegExp("e", "gi")

Upvotes: 19

Related Questions