Presentation is loading. Please wait.

Presentation is loading. Please wait.

Working with Strings.

Similar presentations


Presentation on theme: "Working with Strings."— Presentation transcript:

1 Working with Strings

2 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

3 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)

4 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

5 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.

6 Example See: string_search_case.htm

7 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 an object from the DOM 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 38.0. 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 is present inside the string userBrowser ?

8 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 indexOf()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 //However, is the value is NOT -1, then that means the string 'MSIE 8.0' was present if (location != -1) alert("Sorry, this page does not work with Internet Explorer version 8");

9 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 domain = url.slice(11,18); //The variable holds 'nytimes'

10 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 '

11 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

12 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:

13 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 invoke an extremely useful function called split() 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 split function breaks a long string into smaller pieces, and returns all of those pieces as an array. So in the example below, the variable 'pieces' holds all of the values from the string 'student1' that were separated by commas as separate variables: 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!!!

14 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.


Download ppt "Working with Strings."

Similar presentations


Ads by Google