Tuesday, August 17, 2010

Many ways of splitting string in AS3

In this tutorial we will learn various ways of splitting strings to return a specific part or elements of the string.

There are 4 methods for this: substring, substr, slice and split. All are applied to strings.

Substring returns a part of the string with specified starting and ending indexes (character positions).
Substr returns a part of the string with specified starting position and length of the returned string.
Slice does the same as substring, however substring gives he string between 2 indexes used even if the first parameter is greater than the second. If end is greater than start when using slice, it will return "".
Split returns an array of substrings, separated by a specified symbol (or more than one symbol) - delimeter. Element limit, the second paramter, is optional.

Here are a few examples:

var str:String="Lorem ipsum dolor sit amet, consectetur adipiscing elit."
// returns: 'ipsum do'

// returns: 'ipsum dolor si'

// returns: 'ipsum do'

// returns: 'Lor,m ipsum dolor sit am,t, cons,ct'

// returns: 'Lor,m ipsum dolor sit am,t, cons,ct,tur adipiscing ,lit.'

Here is a little utility I made. Write some text, choose a method (substring, substr, slice, split), enter paremeters and hit 'TEST'.

That's all, folks!


chengchen de said...

I would like to get the first digit after the decimal point. This is the calculation result from a root squared number. Anybody can help?

Francesco said...

Nice little tool, thank you!

Post a Comment