Chapter 7 PowerPoint
Download
Report
Transcript Chapter 7 PowerPoint
JavaScript Chapter 7
Working with Strings
String Operations (Chap 2)
•
•
•
•
•
var colors = “red blue”;
var sizes = ‘small large’;
colors += ‘ green orange’;
sizes = sizes + “ medium XXXL”;
The following are true:
–
–
–
–
(colors == ‘red blue green orange’)
(sizes == “small large medium XXXL”)
(“one” < “two”) //alphabetical ordering
(“ten” > “five”) //alphabetical ordering
Substring Functions (Chap 7)
•
•
•
•
•
•
•
•
var apple = “Macintosh”;
(apple.length == 9)
(apple.charAt(0) == ‘M’)
(apple.charAt(8) == “h”)
(apple.indexOf(“t”) == 5)
(apple.indexOf(“x”) == -1)
(apple.substring(3, 5) == ‘in’)
(apple.substr(3, 2) == “in”)
Numbers in Strings (Chap 7)
• alert ( a ); is really alert (a.toString());
– .toString() converts any variable to a string
– In most cases, JavaScript does this automatically
• parse functions convert strings to numbers
–
–
–
–
–
–
var str = ’66.6 percent’;
(parseInt(str) == 66)
(parseFloat(str) == 66.6)
var nanstr = “not a number 1”;
(parseInt(nanstr) == NaN)
(parseFloat(nanstr) == NaN)
String Parsing Functions (Chap 7)
• Split and Join
• var name = “Dr Sam J Smith III”;
• var words = name.split(“ “);
– (words[0] == “Dr”)
– (words[4] == ‘III’)
– (words.length == 5)
• var name2 = words.join(‘ ‘);
– (name == name2)
String Parsing Functions (Chap 7)
• UPPERCASE & lowercase
• var name = “Dr Sam J Smith III”;
• (name.toUpperCase() == ‘DR SAM J
SMITH III’)
• (name.toLowerCase() == “dr sam j smith
iii)
• These are used to perform caseindependent comparisons.
Exercise 1 & 2 – Modification
• Write HTML to display a text field and a
button.
• Pass the text field to a JavaScript function
that removes things like Mr and Mrs from
before the name and Jr and MD from after
the name and alerts to remaining name.
Exercise 1
•
•
•
•
•
•
function strip(name)
{
var words = name.split(“ “);
var j = words.length-1;
var list = (“Jr”, ‘Sr’, “III”, ‘MD’);
for (var i=0; i<list.length; i++)
– {
– if (list[i] == words[j]) words[j] = “”;
– }
• return words.join(“ “);
• }
Exercise 1 – Important Operations
•
•
•
•
•
Split name string into words
Have a array of target strings
Use a for loop to check all target strings
Join the strings back together
Challenges:
– What happens with extra spaces?
– Can you use one function to check for Mr and Mrs
before the name and Jr and Sr after the name?
Exercise 2
•
•
•
•
•
•
function strip(name)
{
name.toUpperCase();
var words = name.split(“ “);
var list = (“JR”, ‘SR’, “III”, ‘MD’);
for (var i=0; i<list.length; i++)
– {
– if (list[i] == words[j]) words[j] = “”;
– }
• return words.join(“ “);
• }
Exercise 2 – Important Operations
• Use .toUpperCase() or .toLowerCase() to be
•
•
case independent
Find a way to ignore .’s without doubling the
number of entries in the list
Challenges:
– Can you return the name with the original uppercase
and lowercase characters?
– Can you correctly strip Mrs. Lady Sara J Jones MD
Ph.D. Esquire?