Change A Character In A String Using Actionscript

Joshua picture Joshua · May 14, 2010 · Viewed 11.8k times · Source

What is the opposite of String.charAt()??

If I Have a string:

var Str:String="Hello World";

How do I change the 5th character, for example, from a ' ' to an '_'?

I can GET the 5th character like this:

var C:String=Str.charAt(5);

But how do I SET the 5th character?

Thanks in advance.

Answer

Juan Pablo Califano picture Juan Pablo Califano · May 14, 2010

There are many ways to skin this cat. One, off the top of my head, would involve String.substr:

var Str:String="Hello World"
var newStr:String = Str.substr(0,5) + "_" + Str.substr(6);

or, the same as above, but more generalized:

function setCharAt(str:String, char:String,index:int):String {
    return str.substr(0,index) + char + str.substr(index + 1);
}