Java Reference
In-Depth Information
reversing the Order of text
trY it out
Let's create a short example using the split() method, in which you reverse the lines written in a
<textarea> element:
<!DOCTYPE html>
 
<html lang="en">
<head>
<title>Chapter 6, Example 1</title>
</head>
<body>
<script>
var values = prompt("Please enter a set of comma separated values.",
"Apples,Oranges,Bananas");
 
function splitAndReverseText(csv) {
var parts = csv.split(",");
parts.reverse();
 
var reversedString = parts.join(",");
 
alert(reversedString);
}
 
splitAndReverseText(values);
</script>
</body>
</html>
Save this as ch6 _ example1.html and load it into your browser. Use the default value in the prompt
box, click OK, and you should see the screen shown in Figure 6-1.
Try other comma‐separated values to test it further.
The key to how this code works is the function splitAndReverseText() . It accepts a string value that
should contain one or more commas. You start by splitting the value contained within csv using the
split() method and putting the resulting array inside the parts variable:
function splitAndReverseText(csv) {
var parts = csv.split(",");
This uses a comma as the separator. You then reverse the array of string parts using the Array object's
reverse() method:
parts.reverse();
With the array now reversed, it's just a simple matter of creating the new string. You can easily
accomplish this with the Array object's join() method:
var reversedString = parts.join(",");
Search WWH ::




Custom Search