Skip to main content
Pouradam
Inspiring
November 2, 2013
Answered

how to Replace a text inside an Array.

  • November 2, 2013
  • 8 replies
  • 1267 views

Hi there!

This is a sample code to demonstrate what I want:

var str:String = "This@ is\nJust a\ntest and\nI@ am\nTesting";

var a:Array = str.split("\n");

for (var i:uint = 0;i<a.length;i++)

{

          a.replace("@","#");

          trace(a);

}

What I'm getting is:

This@ is

Just a

test and

I@ am

Testing

What I'm EXPECTING to get is:

This# is

Just a

test and

I# am

Testing

Any help would be appreciated please. thanks a lot.

This topic has been closed for replies.
Correct answer kglad

Can you kindly let me know how should I write that for-loop please??

I wrote like this :

var str:String = "This@ is\nJust a\ntest and\nI@ am\nTesting";

var a:Array = str.split("\n");

var regEXP:RegExp = /@/g;

for (var i:uint = 0;i<a.length;i++)

{

          a.replace(regEXP,"#");

          trace(a);

}

And here is the result:

This@ is

Just a

test and

I@ am

Testing

What am I doing wrong??


use:

var str:String = "This@ is\nJust a\ntest and\nI@ am\nTesting";

var a:Array = str.split("\n");

var regEXP:RegExp = /@/g;

for (var i:uint = 0;i<a.length;i++)

{

          a=a.replace(regEXP,"#");

         // trace(a);

}

// but you will achieve better performance using split.join.  (in general, only use regexp for complex manipulation that's near-impossible with the string methods.)

for (var i:uint = 0;i<a.length;i++)

{

          a=a.split("@").join("#");

          //trace(a);

}


8 replies

kglad
Community Expert
Community Expert
November 2, 2013

use:

var str:String = "This@ is\nJust a\ntest and\nI@ am\nTesting";

str=str.split("@").join("#");trace(str);
trace(str);

or

var regEXP:RegExp = /@/g;

trace(str.replace(regEXP,"#"));

Pouradam
PouradamAuthor
Inspiring
November 2, 2013

Thanks a lot for your prompt reply. YES that works, but the problem is my large DATA is already SPLITED into an Array (based on \n ) and now I need to do some amandments in the data that are already stored in the Array.

Is there any way I do the replace INSIDE an index of an Array??

For example I want to replace some data in a[2314] .

Instead of your givven code:

var regEXP:RegExp = /@/g;

trace(str.replace(regEXP,"#"));

Can I use something like this for instance:

var regEXP:RegExp = /@/g;

trace(a[3].replace(regEXP,"#"));

???

(I get no Errors, But also does not work).

kglad
Community Expert
Community Expert
November 2, 2013

you can either apply the code i suggested before creating your array from your string or, if it must be done afterwards, apply either solution to each member of your array (using a for-loop).