Sunday, August 22, 2010

Replacing substrings in a string using AS3

Today we will learn how to replace substrings that match a pattern.

You can find and replace a piece of text according to a pattern using the replace() method:

var str:String = "Seth at Sainsbury's sells thick socks."
var pattern:RegExp = /S/
trace(str.replace(pattern, "Z"));

Output: Zeth at Sainsbury's sells thick socks.

Notice that only one match was replaced. To do more replacements, add "g" (global) flag:

var str:String = "Seth at Sainsbury's sells thick socks."
var pattern:RegExp = /S/g
trace(str.replace(pattern, "Z"));

Output: Zeth at Zainsbury's sells thick socks.

If you want to ignore case-sensitivity, add "i" (ignoreCase) flag.

var str:String = "Seth at Sainsbury's sells thick socks."
var pattern:RegExp = /S/gi
trace(str.replace(pattern, "Z"));

Output: Zeth at ZainZbury'Z ZellZ thick ZockZ.

You can add special $ codes in the pattern here. Here are the meanings of all the possible codes:

$$ - $ symbol

$& - Matched substring.

$` - The string part after the matched substring.

$' - The string part before the matched substring.

$n - A matched n group, where n is a 1-9 number.

$nn - A matched nn group, where nn is a 01-99 number. If the nn group doesn't exist, blank string is used instead.

Here are a few examples:

var str:String = "Seth at Sainsbury's sells thick socks."

trace(str.replace(/S/g, "$$"));

// Output: $eth at $ainsbury's sells thick socks.

trace(str.replace(/S/, "$`"));

// Output: eth at Sainsbury's sells thick socks.

trace(str.replace(/(Seth)( at )(Sainsbury)/g, "$3$2$1"));

// Output: Sainsbury at Seth's sells thick socks.

As you can see, this method isn't really hard to understand, but can be very useful when working with strings.

Hope this helped, thanks for reading!

No comments:

Post a Comment