1 / 43

JavaScript, Fourth Edition

JavaScript, Fourth Edition. Chapter 7 Manipulating Data in Strings and Arrays. Objectives. Manipulate strings Work with regular expressions Manipulate arrays Convert between strings and arrays . JavaScript, Fourth Edition . 2. 2. Manipulating Strings. Parsing

tien
Download Presentation

JavaScript, Fourth Edition

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JavaScript, Fourth Edition Chapter 7 Manipulating Data in Strings and Arrays

  2. Objectives • Manipulate strings • Work with regular expressions • Manipulate arrays • Convert between strings and arrays JavaScript, Fourth Edition 2 2 JavaScript, Fourth Edition

  3. Manipulating Strings • Parsing • Extracting characters or substrings from a larger string • To parse the text strings in your scripts • Use methods and length property of the String class • String class • Represents all literal strings and string variables in JavaScript • Contains methods for manipulating text strings JavaScript, Fourth Edition

  4. Manipulating Strings (continued) JavaScript, Fourth Edition 4

  5. Formatting Strings • Using special characters • For basic types you can use escape sequences • http://www.c-point.com/javascript_tutorial/special_characters.htm • For other special characters, use Unicode • Standardized set of characters from many of the world’s languages • fromCharCode() method • Constructs a text string from Unicode character codes http://en.wikipedia.org/wiki/Unicode JavaScript, Fourth Edition

  6. Formatting Strings <script type="text/javascript">document.write(String.fromCharCode(72,69,76,76,79)); </script> The output of the code above will be: HELLO • Changing case • toLowerCase() and toUpperCase() method JavaScript, Fourth Edition

  7. Formatting Strings (continued) Changing case (continued) Example Modify the e-mail form so it converts the case of the e-mail addresses to lowercase letters JavaScript, Fourth Edition 7

  8. Counting Characters in a String length property Returns the number of characters in a string Syntax stringName.length Example Modify the script so it uses the length property to prevent users from entering a subject of more than 40 characters JavaScript, Fourth Edition 8

  9. Finding and Extracting Characters and Substrings JavaScript, Fourth Edition

  10. Replacing Characters and Substrings replace() method Creates a new string with all instances of a specified pattern replaced with the value of the text argument Example var email = "president@whitehouse.gov"; var newEmail = email.replace("president", "vice.president"); document.write("<p>" + newEmail + "</p>"); // prints 'vice.president@whitehouse.gov' JavaScript, Fourth Edition 10

  11. Combining Characters and Substrings Combine strings using concatenation operator (+) And compound assignment operator (+=) concat() method Creates a new string by combining strings that are passed as arguments Example var name = "Theodor Seuss Geisel"; var penName = "Dr. Seuss"; document.write("<p>" + penName.concat(" was the pen name of ", name) + ".</p>"); JavaScript, Fourth Edition 11

  12. Comparing Strings Comparison operator (==) can be used with strings Compare individual characters according to their Unicode position localeCompare() method Compares strings according to the particular sort order of a language or country Performs a case-sensitive comparison of two strings Example Determine whether a user entered the same e-mail address for the sender and recipient JavaScript, Fourth Edition 12

  13. Comparing Strings Example Determine whether a user entered the same e-mail address for the sender and recipient JavaScript, Fourth Edition 13

  14. Comparing Strings Example Determine whether a user entered the same e-mail address for the sender and recipient String.localeCompare(string) This IE specific method is supported by Firefox and Opera (support elsewhere may be spotty and Opera returns unusual, but usable, results). This method compares the string with the passed value. If the comparison string sorts lower than the original string then this method returns 1 (in opera test for any positive value). If the two strings are equal, this method returns 0, and if the comparison string sorts higher than the original string then this method returns -1 (Search for any negative value in Opera). Firefox 2.0 supports this method, however it is not documented so it's not possible to tell when support for this method began. The documentation indicates that this comparison works regardless of the language being used (Japanese for instance). Since this is not documented in Firefox, the localization support may be imperfect. JavaScript, Fourth Edition 14

  15. Comparing Strings Example Determine whether a user entered the same e-mail address for the sender and recipient var str = 'Hello Dolly!'; var result = str.localeCompare('Hello Dolly!'); document.writeln(result+'<br>'); // Outputs: 0 var result = str.localeCompare('Hello Bolly!'); document.writeln(result+'<br>'); // Outputs: 1 var result = str.localeCompare('Hello Molly!'); document.writeln(result+'<br>'); // Outputs: -1 JavaScript, Fourth Edition 15

  16. Working with Regular Expressions Regular expressions A regular expression is an object that describes a pattern of characters. Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text. Patterns that are used for matching and manipulating strings according to specified rules http://www.w3schools.com/jsref/jsref_obj_regexp.asp With scripting languages Regular expressions are most commonly used for validating submitted form data JavaScript, Fourth Edition 16

  17. Defining Regular Expressions in JavaScript Regular expressions must begin and end with forward slashes * Syntax var txt = new RegExp(pattern,modifiers);or more simply:* var txt = /pattern/modifiers; Example varurlProtocol = /https/; Can use regular expressions with several String class methods search(), replace() Values passed can be a ‘regular expression’ or text string Can also pass the pattern directly to a method RegExp object Contains methods and properties for working with regular expressions in JavaScript JavaScript, Fourth Edition 17

  18. Defining Regular Expressions in JavaScript (continued) Example Modify the search() method in the validateEmail() function So it searches for the ampersand in the e-mail addresses using a regular expression function validEmail(email) { if (/@/.test(email) == false) alert("You must have an @ in the e-mail address"); document.form1.sender_email.value = ""; } JavaScript, Fourth Edition 18

  19. Using Regular Expression Methods RegExp object includes two methods, test() and exec() test() method Returns a value of true if a string contains text that matches a regular expression or false if it doesn’t Syntax var pattern = test(string); The real power of regular expressions comes from the patterns you write JavaScript, Fourth Edition 19

  20. Writing Regular Expression Patterns Hardest part of working with regular expressions is writing the patterns and rules Example emailPattern = /^[_a-z0-9\-]+(\.[_a-z0-9\-] +)*@[a-z0-9\-]+(\.[a-z0-9\-]+)*(\.[a-z]{2,3})$/; / / begin & end ^metacharacter matches at the beginning of a string [ ] match a range of characters i.e. a-z 0-9 \ Id’s the next character as a literal value + Specifies one or more of the preceding characters must match * Specifies one or more of the preceding characters may match {n1,n2} Specifies the preceding character repeat at least n1 times but no more than n2 times $ Matches characters at the end of a string ( ) Specifies required characters to include in a pattern match Note there is a misprint on pg 347..pg 354 is correct!!! JavaScript, Fourth Edition 20

  21. Writing Regular Expression Patterns Regular expression patterns consist of literal characters and metacharacters Special characters that define the pattern matching rules in a regular expression JavaScript, Fourth Edition 21

  22. Writing Regular Expression Patterns (continued) JavaScript, Fourth Edition 22

  23. Writing Regular Expression Patterns (continued) Matching any character Period (.) Matches any single character in a pattern Specifies that the pattern must contain a value where the period is located Matching characters at the beginning or end of a String ^metacharacter Matches characters at the beginning of a string $ metacharacter Matches characters at the end of a string JavaScript, Fourth Edition 23

  24. Writing Regular Expression Patterns (continued) Matching characters at the beginning or end of a String (continued) Anchor Pattern that matches the beginning or end of a line Matching special characters Precede the character with a backslash Example Modify the conditional expression in the validateEmail() function So it uses test() methods and determines whether a domain identifier is appended to the domain name with period JavaScript, Fourth Edition 24

  25. Writing Regular Expression Patterns (continued) Specifying quantity Quantifiers Metacharacters that specify the quantity of a match Specifying subexpressions Subexpression or subpattern Characters contained in a set of parentheses within a regular expression Allow you to determine the format and quantities of the enclosed characters as a group JavaScript, Fourth Edition 25

  26. Writing Regular Expression Patterns (continued) JavaScript, Fourth Edition 26

  27. Writing Regular Expression Patterns (continued) Defining character classes Character classes Used in regular expressions to treat multiple characters as a single item Created by enclosing the characters that make up the class with bracket [] metacharacters Use a hyphen metacharacter (-) to specify a range of values in a character class Specify optional characters to exclude in a pattern match Include the ^ metacharacter immediately before the characters in a character class JavaScript, Fourth Edition 27

  28. Writing Regular Expression Patterns (continued) Defining character classes (continued) Regular expressions include special escape characters in character classes To represent different types of data JavaScript, Fourth Edition 28

  29. Writing Regular Expression Patterns (continued) Defining character classes (continued) Example Modify the validateEmail() function so it uses an e-mail regular expression to validate e-mail addresses Matching multiple pattern choices Allow a string to contain an alternate set of substrings Separate the strings in a regular expression pattern with the | metacharacter JavaScript, Fourth Edition 29

  30. Setting Regular Expression Properties • http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_regexp_g_2 • Options for setting the values of these properties • Assign a value of true or false to the property • By creating a regular expression with the RegExp() constructor • Use the flags when you assign a regular expression to a variable without using the RegExp() constructor JavaScript, Fourth Edition 30

  31. Manipulating Arrays • Use the methods and length property of the Array class • When you create an array • You are instantiating an object from the Array class • Example • Modify the recipient section of the e-mail form in order to allow users to enter multiple recipients JavaScript, Fourth Edition 31

  32. Manipulating Arrays (continued) JavaScript, Fourth Edition 32

  33. Finding and Extracting Elements and Values Primary method for finding a value in an array Use a looping statement to iterate through the array until you find a particular value Extract elements and values from an array Use the slice() method to return (copy) a portion of an array and assign it to another array JavaScript, Fourth Edition 33

  34. Manipulating Elements • Adding and removing elements from the beginning of an array • shift() method removes and returns the first element from the beginning of an array • unshift() method adds one or more elements to the beginning of an array • Adding and removing elements from the end of an array • Use array’s length property to determine the next available index JavaScript, Fourth Edition

  35. Manipulating Elements (continued) Adding and removing elements from the end of an array (continued) pop() method removes the last element from the end of an array push() method adds one or more elements to the end of an array Adding and removing elements within an array Use the splice() method Also renumbers the indexes in the array Methods of the Array class are not available to a form’s options[] array JavaScript, Fourth Edition 35

  36. Manipulating Elements (continued) Adding and removing elements within an array (continued) Example Modify the recipient functions in the e-mail form so they use methods of the Array class to add and delete recipients JavaScript, Fourth Edition 36

  37. Manipulating Arrays Sorting arrays Sort elements of an array alphabetically Use the sort() method reverse() method Simply transposes, or reverses, the order of the elements in an array Combining arrays Use the concat() method Syntax array1.contact(array2, array3, ...); JavaScript, Fourth Edition 37

  38. Converting Between Strings and Arrays split() method of the String class Splits a string into an indexed array Syntax array = string.split(separator[, limit]); To split individual characters in a string into an array Pass an empty string ("") as the separatorargument JavaScript, Fourth Edition 38

  39. Converting Between Strings and Arrays (continued) join() method of the Array class Combines array elements into a string, separated by a comma or specified characters Syntax array.join(["separator"]); To prevent the elements from being separated by any characters in the new string Pass an empty string ("") as the separatorargument JavaScript, Fourth Edition 39

  40. Converting Between Strings and Arrays (continued) You can also use the toString() and toLocaleString() method To convert an array to a string Example Add code to the e-mail form that allows you to update recipient information and to submit the recipient’s list as a single string JavaScript, Fourth Edition 40

  41. Summary • Parsing refers to the act of extracting characters or substrings from a larger string • All literal strings and string variables in JavaScript are represented by the String class • The fromCharCode() method of the String class constructs a text string from Unicode character codes • To change the case of letters in a string, use the toLowerCase() and toUpperCase() methods JavaScript, Fourth Edition

  42. Summary (continued) • String class • length property • Methods: replace(), concat(), localeCompare() • Regular expressions are patterns used for matching and manipulating strings according to specified rules • RegExp object contains methods and properties for working with regular expressions in JavaScript JavaScript, Fourth Edition

  43. Summary (continued) Use the methods and length property of the Array class to manipulate arrays in your scripts Methods: slice(), shift() and unshift(), pop() and push(), splice(), sort(), reverse(), concat(), and join() The split() method of the String class splits a string into an indexed array JavaScript, Fourth Edition 43

More Related