Title: JavaScript, Fourth Edition
1JavaScript, Fourth Edition
- Chapter 7
- Manipulating Data in Strings and Arrays
2Objectives
- Manipulate strings
- Work with regular expressions
- Manipulate arrays
- Convert between strings and arrays
JavaScript, Fourth Edition
2
2
3Manipulating 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
4Manipulating Strings (continued)
JavaScript, Fourth Edition
4
5Formatting Strings
- Using special characters
- For basic types you can use escape sequences
- For other special characters, use Unicode
- Standardized set of characters from many of the
worlds languages - fromCharCode() method
- Constructs a text string from Unicode character
codes - Changing case
- toLowerCase() and toUpperCase() method
6Formatting 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
6
7Counting 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
7
8Finding and Extracting Characters and Substrings
9Replacing 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_at_whitehouse.gov"
- var newEmail email.replace("president",
"vice.president") - document.write("ltpgt" newEmail "lt/pgt") //
prints - 'vice.president_at_whitehouse.gov'
JavaScript, Fourth Edition
9
10Combining 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("ltpgt" penName.concat(" was the
pen name of ", name) ".lt/pgt")
JavaScript, Fourth Edition
10
11Comparing 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
11
12Working with Regular Expressions
- Regular expressions
- Patterns that are used for matching and
manipulating strings according to specified rules - With scripting languages
- Regular expressions are most commonly used for
validating submitted form data
JavaScript, Fourth Edition
12
13Defining Regular Expressions in JavaScript
- Regular expressions must begin and end with
forward slashes - Example
- var urlProtocol /https/
- Can use regular expressions with several String
class methods - 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
13
14Defining 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
JavaScript, Fourth Edition
14
15Using 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
doesnt - Syntax
- var pattern test(string)
- The real power of regular expressions comes from
the patterns you write
JavaScript, Fourth Edition
15
16Writing Regular Expression Patterns
- Hardest part of working with regular expressions
is writing the patterns and rules - Example
- emailPattern /_a-z0-9\\-(\._a-z0-9\\-
- )_at_a-z0-9\\-(\.a-z0-9\\-)(\.a-z2,3)/
- Regular expression patterns consist of literal
characters and metacharacters - Special characters that define the pattern
matching rules in a regular expression
JavaScript, Fourth Edition
16
17Writing Regular Expression Patterns (continued)
JavaScript, Fourth Edition
17
18Writing 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
18
19Writing 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
19
20Writing 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
20
21Writing Regular Expression Patterns (continued)
JavaScript, Fourth Edition
21
22Writing 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
22
23Writing 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
23
24Writing 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
24
25Setting Regular Expression Properties
- 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
25
26Manipulating 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
26
27Manipulating Arrays (continued)
JavaScript, Fourth Edition
27
28Finding 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
28
29Manipulating 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 arrays length property to determine the next
available index
30Manipulating 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
forms options array
JavaScript, Fourth Edition
30
31Manipulating 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
31
32Manipulating 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
32
33Converting 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 separator
argument
JavaScript, Fourth Edition
33
34Converting 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 separator
argument
JavaScript, Fourth Edition
34
35Converting 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
recipients list as a single string
JavaScript, Fourth Edition
35
36Summary
- 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
37Summary (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
38Summary (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
38