PDA

View Full Version : Replacing words in a string - best way?


handycam
08-12-2007, 12:05 AM
I've got a string where I need to replace multiple instances of a word with a string.

A simpler example would be "Four score and # years ago" -- where I need to insert a string variable instead of "#".

I have been doing something like:


var re : RegExp = /(#+)/ ;
var _results:Array = _myString.split(re);
trace(_results);

And my plan was to use "results.splice()" to add the string. However, in the real string there are several "#" to replace, and it seems my way would get unwieldy.

Is there a more efficient way?

Flash Gordon
08-12-2007, 12:22 AM
http://actionscript.org/forums/showthread.php3?t=143761&highlight=replace

make a loop and compare the results of your method vs. that one. See which is faster.

drkstr
08-12-2007, 12:29 AM
Is this what you are trying to do?


var reg:RegExp = /#+/gm;
String("Hello #!").replace(reg, 'World');



Regards,
...aaron

*edit*
Don't forget to add the correct mode (terminoligy?) after the regex expression. The g tells it to match all instances. I forget off the top of my head what the m is. Maybe don't even need it. There is a good livedocs article that gives a primer to regex. I'm sure it will explain what its for.

*edit again*
I got off my lazy ass and looked it up. I just hate not knowing something! ;-)

The 'm' tells the regex there are multiple lines of text (which effects word boundries if you're interested). Also to correct my previous mistake, it's called a flag not a mode.

Here are the details.

http://livedocs.adobe.com/flex/2/docs/00001907.html