Working with Strings. Learning Objectives By the end of this lecture, you should be able to: – Appreciate the need to search for and extract information.

Slides:



Advertisements
Similar presentations
Lesson 6D – Loops and String Arrays – split process By John B. Owen All rights reserved ©2011.
Advertisements

Modifying existing content Adding/Removing content on a page using jQuery.
Events Part III The event object. Learning Objectives By the end of this lecture, you should be able to: – Learn to use the hover() function – Work with.
Form Validation. Learning Objectives By the end of this lecture, you should be able to: – Describe what is meant by ‘form validation’ – Understand why.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 17 JavaScript.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Escaping Characters document.write(). Learning Objectives By the end of this lecture, you should be able to: – Recognize some of the characters that can.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Introduction to scripting
Random Stuff Colors Sizes CSS Shortcuts. Learning Objectives By the end of this lecture, you should be able to: – Identify the 3 most common ways in which.
XP Tutorial 14 New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
JavaScript: Control Structures September 27, 2005 Slides modified from Internet & World Wide Web: How to Program (3rd) edition. By Deitel, Deitel,
Tutorial 14 Working with Forms and Regular Expressions.
Using the API. Learning Objectives By the end of this lecture, you should be able to: – Identify what is meant by an ‘API’ – Know how to look up functions.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
1 JavaScript: Objects and Object Models October 25, 2005 Slides modified from Internet & World Wide Web: How to Program (3rd) edition. By Deitel,
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
Chapter 8 Cookies And Security JavaScript, Third Edition.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
JavaScript – Part IV Event Handlers, Images, Window object William Pegram George Mason University June 3, 2010.
Introduction to JavaScript 41 Introduction to Programming the WWW I CMSC Winter 2004 Lecture 17.
Regular Expression (continue) and Cookies. Quick Review What letter values would be included for the following variable, which will be used for validation.
Chapter 5: Windows and Frames
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
Working with Files. Learning Objectives By the end of this lecture, you should be able to: – Examine a file that contains code with unfamiliar material,
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 24 The String Section.
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
Dr. Qusai Abuein1 Internet & WWW How to program Chap.(6) JavaScript:Introduction to Scripting.
1 A Balanced Introduction to Computer Science David Reed, Creighton University ©2005 Pearson Prentice Hall ISBN X Chapter 4 JavaScript and.
Project 1: Using Arrays and Manipulating Strings Essentials for Design JavaScript Level Two Michael Brooks.
A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University ©2011 Pearson Prentice Hall ISBN Chapter 17 JavaScript.
Modifying HTML attributes and CSS values. Learning Objectives By the end of this lecture, you should be able to: – Select based on a class (as opposed.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
CSC Programming I Lecture 9 September 11, 2002.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming strings.
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
IS2802 Introduction to Multimedia Applications for Business Lecture 8: JavaScript and Cookies Rob Gleasure
Review of HTML and CSS A (very) brief review of some key fundamentals to be aware of in IT-238.
XP Tutorial 7 New Perspectives on JavaScript, Comprehensive 1 Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
JavaScript: Objects 1 © by Pearson Education, Inc. All Rights Reserved.
Chapter 23 The String Section (String Manipulation) Clearly Visual Basic: Programming with Visual Basic nd Edition.
Introduction to Arrays. Learning Objectives By the end of this lecture, you should be able to: – Understand what an array is – Know how to create an array.
1 JavaScript and Dynamic Web Pages Lecture 7. 2 Static vs. Dynamic Pages  A Web page uses HTML tags to identify page content and formatting information.
Java Script: Objects (Chapter 12 in [2]). 2 Outline Introduction Introduction Thinking About Objects Thinking About Objects Math Object Math Object String.
JavaScript Part 1 Introduction to scripting The ‘alert’ function.
JavaScript: Conditionals contd.
JavaScript Controlling the flow of your programs with ‘if’ statements
Moving away from alert() Using innerHTML Using an empty div section
Regular Expressions 'RegEx'.
Chapter 6 JavaScript: Introduction to Scripting
Database application MySQL Database and PhpMyAdmin
Introduction to Scripting
Retrieving information from forms
In Class Program: Today in History
WEB PROGRAMMING JavaScript.
Week 9 – Lesson 1 Arrays – Character Strings
'Boolean' data type.
JavaScript: Objects.
String Processing 1 MIS 3406 Department of MIS Fox School of Business
JavaScript: Introduction to Scripting
Chapter 17 JavaScript Arrays
Working with Strings.
Events Part III The event object.
Reading information from files
Random Stuff Colors Sizes CSS Shortcuts.
Using the API.
Retrieving information from forms
Presentation transcript:

Working with Strings

Learning Objectives By the end of this lecture, you should be able to: – Appreciate the need to search for and extract information from strings – Be able to apply some new JavaScript String functions using JavaScript – in particular, the split() function – Note: This lecture requires an understanding of arrays. If you are not yet comfortable with the fundamentals of arrays, you should go back and review before proceeding

A String is simply an array of characters This is important – be sure you are clear on this concept! Suppose we have a string as demonstrated here: var url = " The variable ' url ' holds the string. Internally, the string is stored as an array of characters like so: Therefore, we can do the following: alert( url[7] ); //would output a 'w' alert( url.length ); //would output 21 (since the string holds 21 characters)

Length of a String Sometimes you want to determine the length of a string. For example, imagine that you have asked the user to create a password and that the password must be a minimum of 6 characters. Because a string is an array, we can use the ' length ' property to determine its length: function validatePassword() { var password = $('#txtPassword').val(); var lengthOfPassword = password.length; //Note no parentheses since 'length' is not a function if (lengthOfPassword < 6) alert('Your password must be at least 6 characters'); } Somewhere in your page, you could verify that a user has entered a valid password by typing: $('#txtPassword').blur( validatePassword() ); //Recall that 'blur' event fires when the user leaves a form element

Changing the case of a String There may be times when you want to convert a string to all upper-case or all lower-case letters. For example, imagine that you have asked the user to type the name of their favorite animal, and you are going to search a database to see if you have a photo of that animal. Now suppose that your database is case sensitive. Your database holds all values in lower case (e.g. cat, dog, platypus, etc). What if the user types (' Cat ', or ' CAT ')? A case- sensitive database would not find it. Therefore, we will convert the user's entry into lower case before submitting the query to the database. Let's use a JavaScript function to convert to upper case. The function is called toUpperCase(). There is also a corresponding toLowerCase(). var favoriteAnimal = $('#txtFavAnimal').val(); //retrieve the value from the form favoriteAnimal = favoriteAnimal.toLowerCase(); //convert to lower case We can now search the database using the ' favoriteAnimal ' variable which is now in all lower-case letters.

Example See: string_search_case.htm

Searching inside a String In JavaScript, we use the function indexOf() to determine if some text is present inside a String. For example, suppose you want to determine whether the visitor to your page is using an older version of Internet Explorer – a version that you know does not work properly with your site. Let's say that the problematic browser is Internet Explorer version 8. (In fact, compatibility issues with this particular browser was a real issue a few years ago). We will start by using a special built-in object called the ' Navigator ' to determine which version of browser our viewer is using: var userBrowser = navigator.userAgent; ' navigator.userAgent ' is a special object that returns a string with details about the browser that your viewer is using to browse your page. If you output the ' userBrowser ' string, you would get a long bit of text that might look something like this: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/ Firefox/38.0 This tells us that the user is using Firefox version A user using Internet Explorer version 8 might show: Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/6.0) So how can we determine if this MSIE 8.0 is present inside the string userBrowser ?

Searching inside a String using ' indexOf() ' We can search for a 'substring' (i.e. a string inside a longer string) by using JavaScript's indexOf() function. The indexOf function returns an integer. If the substring that we are looking IS present, the integer that is returned by the function will be the location inside the longer string where the substring was found. var userAgent = "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/6.0)"; var location = userAgent.indexOf("MSIE 8.0"); //the variable 'location' holds 26 If a substring is NOT found, then indexOf() will return -1: var userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/ Firefox/38.0 "; var location = userAgent.indexOf("MSIE 8.0"); // 'location' holds the value –1 //If the user is NOT using MSIE 8.0, then location will hold -1 if (location != -1) alert("Sorry, this page does not work with Internet Explorer version 8");

Extracting part of a String using ' slice() ' Another common bit of string functionality is to pull out part of a string from a larger string. For example, suppose you had a URL: and you wished to extract only the domain segment ( nytimes.com ) for use at some later point. The first argument you provide to the slice() function is where you say that you wish to begin extracting. As always, don't forget that the index always begins at 0. var url = " var domain = url.slice(11); //The variable holds 'nytimes.com' You can also specify exactly how many characters you wish to keep. For example, if all you wanted was 'nytimes ', then you would want to stop extracting before '.com '. In other words, you would want to stop extracting at character number 18. var url = " var domain = url.slice(11,18); //The variable holds 'nytimes'

Example from textbook Suppose the URL was and you wished to extract the entire URL, but without the part: var url = " var domain = url.slice(7); //The variable holds '

slice() also works backwards If you provide a negative number as the argument, slice() will work backwards beginning from the end of the string. var quote = "To be, or not to be."; var subquote = quote.slice(-6); //The variable holds 'to be.' Recall: If you provide a second argument, it will extract from the first argument to the second: subquote = quote.slice(-6,-1); //holds 'to be' without the period

Breaking a string into parts using ' split() ' There are many situations in which a record of information is contained inside a single string, and is delimited by a specific character. For example, some spreadsheets are "comma delimited" which means that each record in the spreadsheet can be viewed in a text document as a single line of text (a String), but with each field (i.e. column) separated by a comma. For example, imagine we were working with the following spreadsheet ( enrollment.csv ) with some student enrollment details: If you opened this CSV file in a in a text editor, you would see:

Using ' split() ' The steps to retrieve information from a file are discussed in a later lecture. For now, let's assume that we have successfully retrieved the first line of student information from our file, and that we have stored this text inside the string student1 : var student1 = "Roberta,Redgrave,1988,2013,YES"; Suppose we wanted to extract only the last name, first name, and enrollment year. We can now use the powerful split() function to break this long string into a series of smaller strings: var pieces = student1.split(','); The argument that we provided to ' split(',') ' -- i.e. the comma -- says that we want to break our long string into a series of shorter strings using a comma as our "delimiter". The variable 'pieces ' now holds all of the values that were separated by commas: pieces[0] //holds 'Roberta' pieces[1] //holds 'Redgrave' pieces[2] //holds '1988' pieces[3] //holds '2013' pieces[4] //holds 'YES' As you can see, the variable pieces is an array. Now to keep only the last name, first name, and enrollment year we can use our array notation: var firstName = pieces[0]; var lastName = pieces[1]; var enrollmentYear = parseInt( pieces[3] ); //NOTE that we should parse this!!!

Bug Alert! (Feel free to ignore for now) I've told you that a string is essentially an array of individual characters. Therefore, can you predict what will be output by the following? var sentence = "Oh brave new world"; sentence[0] = 'U'; alert( sentence ); I would hope that you answered that the alert statement would output: Uh brave new world In fact, however, this is not the case. The reason is that once you have created a string, you can not change it. You can only create a new string over it. Don't worry for now if you don't follow. The key take-away point here is that the statement sentence[0] = 'U'; will NOT work since you are not allowed to modify an existing String. We will not go into further detail here.