17.6.1. Getting the Number of Elements in a String: elements() Function

The elements() function is used to get the number of elements in a string. Its syntax is:


String.elements(string, delimiter);


If the function call succeeds, the number of elements in string is returned. If delimiter is an empty string or an error occurs, an invalid value is returned.

If delimiter is a string that has more than one character, its first character will be used as the delimiter.

It is important to note that an empty string is considered as a valid element. Hence, elements() never returns zero.

Below are some WMLScript examples that can help you understand the usage of elements() better:


var number = String.elements("- WMLScript Tutorial, WML Tutorial -", ",");

After executing the above script, number has the integral value 2 since the string contains the following two elements when using "," as the delimiter:

"- WMLScript Tutorial"
" WML Tutorial -"


var number = String.elements("- WMLScript Tutorial, WML Tutorial -", "-");

After executing the above script, number has the value 3 since the string contains the following three elements when using "-" as the delimiter (remember that an empty string is a valid element):

""
" WMLScript Tutorial, WML Tutorial "
""


var number = String.elements("", ",");

After executing the above script, number has the value 1 since the string contains the following element when using "," as the delimiter:

""


var number = String.elements("- WMLScript Tutorial, WML Tutorial -", "?");

After executing the above script, number has the value 1 since the string contains the following element when using "?" as the delimiter:

"- WMLScript Tutorial, WML Tutorial -"


Previous Page Page 46 of 71 Next Page


A button for going back to the top of this page