Handling Strings . 273 str.charAt(i) is the character (Web hosting packages)
Wednesday, October 31st, 2007Handling Strings . 273 str.charAt(i) is the character for which the loop s blockis currently being executed. The variable i starts at 0, the index of the string s first character, and is incremented each time until it is equal to the index of the string s last character. Suppose the current character is t. The condition looks like this then: list.indexOf(”t”)== 1 If the character t is not found in the string list, the method indexOf() whose argument is t returns 1 exactly the number against which the returned value is tested. If a character is not valid (not found in list), a message is displayed and the function is terminated, indirectly causing the script s execution to end. The function then asks the user to enter the key number, which must be an integer from 1 to 63. Because this is just an example, the input value is not tested. If the user clicks Cancel, the function is terminated. Otherwise, the function continues, and the key number is converted from a numeric string to a number via the parseInt() function. The encoded string, which is returned by the function encode(), is displayed. encode(str, key) At first, an empty string is assigned to the variable code. A loop is used to replace every character of the input string by another character. The index of the current character (the one whose index in str is equal to the loops counter, i)inthe list string is assigned to the variable ind. The bitwise OR operator is given the key number and the value of ind as operands. The character whose index in list is equal to the value returned by the bitwise OR operation is the one used to replace the current character in the new string, so it is assigned to the variable that holds the encoded string. The new string is returned by the function. Summary Strings are a very useful data type in JavaScript. JavaScript tends to organize its elements in the form of objects, so all string-related functions and data are grouped together to form the String object. In this chapter we discussed the methods of the String object, as well as its single property, length. Because strings are direct or indirect (based on the way you create them) instances of this object, you can create prototypes to extend the object s capabilities. The JavaScript example provided at the end of the chapter gives a clear view of the String object s strength. We did not provide many examples in this chapter because string manipulation and handling can be found in almost every example later on in this book. Chapter
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.