www.cisdocs.com

Download Report

Transcript www.cisdocs.com

JavaScript, Fifth Edition
Chapter 7
Manipulating Data in Strings and Arrays
Objectives
In this chapter, you will:
• Manipulate strings
• Work with regular expressions
• Manipulate arrays
• Convert between strings and arrays
JavaScript, Fifth Edition
2
Manipulating Strings
• String
– Text contained within double or single quotation
marks
– Literal values or assigned to a variable
– Begin and end with same type of quotation mark
• Example:
document.write("2003-04 NBA All-Star Game MVP: ");
var basketballPlayer = "Shaquille O'Neal";
document.write("<p>" + basketballPlayer + "</p>");
JavaScript, Fifth Edition
3
String Object
• The String object
– Anytime a text string is created, it is created from the
String object
• Inherits all of the properties and methods of the string
object
– To create strings
stringVariable = new String(“special text")
OR
var txt = “special text";
Manipulating Strings (cont’d.)
• Use String Object to manipulate text
–
–
–
–
–
–
parse (extract) text strings in scripts
Format text
Find text patterns
Replace text
Chop up text
Many properties and methods for manipulating text
strings
JavaScript, Fifth Edition
5
String Object
Properties and methods
– charAt() - Returns the character at the specified index
– concat() - Joins two or more strings, and returns a copy of the joined
strings
– indexOf()-Returns the position of the first found occurrence of a
specified value in a string
– slice() - Extracts a part of a string and returns a new string
– split()- Splits a string into an array of substrings
– substr() -Extracts the characters from a string, beginning at a specified
start position, and through the specified number of character
– toLowerCase- Converts a string to lowercase letters
– toUpperCase - Converts a string to uppercase letters
– search() – Returns the position of the first instance of the first character
specified
– match()returns an array containing the results that match a pattern
– lastIndexOf() – Returns the position of the last found occurrence of a
specified value in a string
Length property
• Length property
– Returns the number of characters of a string
–
stringVar = "GPS-ware Products";
lengthValue = stringVar.length
toUpperCase and toLowerCase
• Changes case
var agency = "fema";
document.write("<p>" + agency.toUpperCase()
+ "</p>");
var agency = "fema";
agency = agency.toUpperCase()
document.write("<p>" + agency + "</p>");
JavaScript, Fifth Edition
8
Search methods
• Two types of string search methods
– Those that return a numeric position in a text string
• search()
• indexOf()
– Those that return a character or substring
• substring()
• slice()
JavaScript, Fifth Edition
9
search() and indexOf()
• searches a string for a specified value and returns
the numeric position of the match
• search():
– string.search(pattern)
– var str=“[email protected]";
var n=str.search(“@"); //returns 3
• indexOf()
– string.indexOf(str, start)
– can specify where in the string to start searching
var email = "[email protected]";
document.write(email.indexOf("@", 10));
// returns -1
JavaScript, Fifth Edition
10
substr () and slice()
• searches a string for a specified value and returns a
character or substring
– doesn’t change original string; starts at 0
– string.substr(start, end)
var str="Hello world!";
document.write(str.substring(3)+"<br>");
document.write(str.substring(3,7));
– string.slice (start, end)
var str = "Hello world!";
var res = str.slice(1,5); //returns ello
JavaScript, Fifth Edition
11
More on slice()
• slice() method allows negative argument values for the index
arguments
– Specifying a negative value for the starting index
• slice() method starts at the end of the text string
– Specifying a negative value for the ending index
• Number of characters the slice() method extracts also starts at
the end of the text string
• slice() method does not return the character represented by the
ending index
– Returns the character immediately before the ending index
– var language = “Javascript”
– language.slice(-6,-3)
// returns scr
– language.slice(-1) //returns t
–
JavaScript, Fifth Edition
12
lastIndexOf()
• returns position of the last occurrence of one string
in another string
– Example:
var phrase = "Hello planet earth, you are a great
planet.";
var loc = phrase.lastIndexOf("planet"); // returns 36
– Use as a starting point for extraction
– phrase.substr(loc); //returns planet
JavaScript, Fifth Edition
13
replace()
– Creates a new string with the first instance of a
specified pattern replaced with the value of the text
argument
– Syntax: string.replace(pattern, text)
– Example:
var email = "[email protected]";
var newEmail = email.replace("president",
"vice.president");
document.write("<p>" + newEmail + "</p>");
// prints '[email protected]'
JavaScript, Fifth Edition
14
Pattern matching
REGULAR EXPRESSIONS
JavaScript, Fifth Edition
16
Introducing Regular Expressions
• A regular expression is an object that describes a pattern
of characters.
• When you search in text, you can use a pattern to
describe what you are searching for.
– A simple pattern can be one single character.
– A more complicated pattern can consist of more
characters.
• Used for pattern-matching
– a text string is tested to see whether it matches a pattern
• Used for "search-and-replace" functions on text
• Used for validating data entered into form fields
Introducing Regular Expressions
• SYNTAX
– You create a regular expression in JavaScript using the
command
var patt = /pattern/modifiers;
• pattern specifies the pattern of an expression
• modifiers are optional – if present, specify if a search should
be global, case-sensitive, etc
• Pattern always starts and ends with a slash
var str=“Hello World. It’s a wonderful World";
var patt1=/world/i; // i modifier forces case insensitive
var str="Is this all there is?";
var patt1=/is/g; // g modifier is global searches for > 1
Using Regular Expression Methods
• RegExp object
– Includes two methods
• test() and exec()
• test() method: returns a value of true or false
• exec() method: returns a result
JavaScript, Fifth Edition
19
Introducing Regular Expressions
• The test() method searches a string for a specified
value, and returns true or false, depending on the
result.
var matchpattern=/e/
var x = "The best things in life are free";
window.alert(matchpattern.test(x)) ;
• This is testing for the presence of an “e” in the
string.
• If found, true will be returned
Introducing Regular Expressions
• The exec() method searches a string for a specified
value, and returns the result (or null if no match
found)
var matchpattern=/e/
var x = "The best things in life are free";
window.alert(matchpattern.exec(x)) ;
• This is testing for the presence of an “e” in the
string.
• If found, the ‘e’ will be returned
Introducing Regular Expressions
• Modifiers
– I - Perform case-insensitive matching
– G - Perform a global match (find all matches rather
than stopping after the first match)
– M - Perform multiline matching
Introducing Regular Expressions
• Position Matching
• match a substring that occurs at a specific location
within the larger string
• a substring that occurs at the very beginning or end of
string.
Introducing Regular Expressions
• Character
Class
matching
• more complex
matches
• /[abc]/ matches
"a", "b", or "c",
while
/[a-zA-Z0-9]/
matches all
alphanumeric
characters.
Introducing Regular Expressions - Brackets used to find a range of characters
[abc] - Find any of these characters between the brackets
[^abc] - Find any other characters not between the brackets
[0-9] - Find any digit from 0 to 9
[A-Z] - Find any character from uppercase A to uppercase Z
[a-z] - Find any character from lowercase a to lowercase z
[A-z] - Find any character from uppercase A to lowercase z
[abcs] - Find any character in the given set
[^abcs] - Find any character outside the given set
(red|blue|yellow) - Find any of the alternatives specified
Introducing Regular Expressions
• Repetition characters
– match character(s) that occurs in certain repetition.
For example, to match "555", the easy way is to use
/5{3}/
Introducing Regular Expressions
Alteration and Grouping
•
group characters to be considered as a single
entity or add an "OR" logic to your pattern matching.
Introducing Regular Expressions
• Escape Sequences
– An escape sequence is a special command inside a
text string that tells the JavaScript interpreter not to
interpret what follows as a character
– The character which indicates an escape sequence in
a regular expression is the backslash character \
Introducing Regular Expressions –
Escape sequences
Writing Regular Expression Patterns
• Hardest part of working with regular expressions
– Writing the patterns and rules
JavaScript, Fifth Edition
30
ARRAYS AND STRINGS
JavaScript, Fifth Edition
31
Using Array Methods
Manipulating Arrays
• Use the Array class methods and length property
to manipulate arrays in scripts
– Methods: slice(), shift() and unshift(),
pop() and push(), splice(), sort(),
reverse(), concat(), and join()
– split() method of the String class splits a string
into an indexed array
• Primary method for finding a value in an array
– Use a looping statement to iterate through the array
until a particular value found
JavaScript, Fifth Edition
33
Slice()
• 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
• Syntax for the slice() method
array_name.slice(start, end);
JavaScript, Fifth Edition
34
shift() and unshift()
• Adding and removing elements to and 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
JavaScript, Fifth Edition
35
pop() and push()
• Adding and removing elements to and from the end
of an array (cont’d.)
– 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
JavaScript, Fifth Edition
36
splice()
• Adding and removing elements within an array
– Use the splice() method
• Also renumbers the indexes in the array
JavaScript, Fifth Edition
37
sort() and concat()
• Sorting arrays
– Sort elements of an array alphabetically
• Use the sort() method
– reverse() method
• Transposes, or reverses, the order of the elements in
an array
• Combining arrays
– Use the concat() method
– Syntax
array1.contact(array2, array3, ...);
JavaScript, Fifth Edition
38
split()
• 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, Fifth Edition
39
join()
• 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 elements from being separated by any
characters in the new string
– Pass an empty string ("") as the separator
argument
JavaScript, Fifth Edition
40