Java Reference
In-Depth Information
Additional String Methods
In this section you will take a look at the split() , replace() , search() , and match() methods, and
see how they work without regular expressions.
The split() Method
The String object's split() method splits a single string into an array of substrings. Where the string
is split is determined by the separation parameter that you pass to the method. This parameter is simply
a character or text string.
For example, to split the string “A,B,C” so that you have an array populated with the letters between
the commas, the code would be as follows:
var myString = “A,B,C”;
var myTextArray = myString.split(',');
JavaScript creates an array with three elements. In the fi rst element it puts everything from the start of
the string myString up to the fi rst comma. In the second element it puts everything from after the fi rst
comma to before the second comma. Finally, in the third element it puts everything from after the sec-
ond comma to the end of the string. So, your array myTextArray will look like this:
A
B
C
If, however, your string were “A,B,C,” JavaScript would split it into four elements, the last element
containing everything from the last comma to the end of the string; in other words, the last string
would be an empty string.
A
B
C
This is something that can catch you off guard if you're not aware of it.
Try It Out Reversing the Order of Text
Let's create a short example using the split() method, in which you reverse the lines written in a
<textarea> element.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8” />
<title>Example 1</title>
<script language=”JavaScript” type=”text/JavaScript”>
function splitAndReverseText(textAreaControl)
{
Search WWH ::




Custom Search