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 well: any idea how to make it random? Relations

+4
source share
2 answers

Just use the String # replace () function.

eg:

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

The first argument to the replace function is a regular expression. You will find information about them all over the Internet . And this handy tool from Grant Skinner is called Regexr , with which you can test your regular ActionScript expressions.

The part between the two slashes (/) is the actual regular expression.

  • " g " after the regular expression means "replace globally" (i.e. all occurrences of the letter "e" in the example, without "g" it will simply replace the first occurrence).
  • i ” means “case insensitive” (in the example without “i”, capital E would not be replaced).

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

+19
source

A quick way may be to make two replacements. One for lowerCase and one for upperCase. It will 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 save the case of your find intact ie:

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

If you do not want this argument to be intact, @RIAstar String.replace() answer was cleaner. (But you could, of course, also use his example twice in this regard)

-1
source

Source: https://habr.com/ru/post/1386093/


All Articles