Advanced Web Programming - Chapter 8 PDF
Document Details
Uploaded by IntelligentJasper852
Tags
Summary
This document is a chapter from a course on advanced web programming. It provides an introduction to JavaScript strings, including primitives, objects, and various methods for working with text. The chapter outlines the basics of strings, covers combining strings, accessing characters, and more, suitable for an undergraduate-level course in web development.
Full Transcript
Advanced Web Programming Chapter 8: Types, Primitives, and Objects Strings IN THIS CHAPTER Understand what Objects is about Learn about the basic types in JavaScript Learn about primitives Learn about Strings Types in JavaScript The basic types in JavaScript are...
Advanced Web Programming Chapter 8: Types, Primitives, and Objects Strings IN THIS CHAPTER Understand what Objects is about Learn about the basic types in JavaScript Learn about primitives Learn about Strings Types in JavaScript The basic types in JavaScript are String, Number, Boolean, Null, Undefined, and Object. Some of these types may be very familiar to you already, and some of them may not be. Types can be simple or complex as well. In JavaScript terminology involving types, simple and complex are more formally known as primitive and object respectively. The primitive types are your String, Number, Boolean, Null, and Undefined types What are Objects? Objects come in different shapes, sizes, and usefulness. Despite the variations, objects are all the same at a high level. They are an abstraction. The Predefined Objects are displayed in Table 11.2 What are Objects? (Cont…) Each object has its own special regarding how you can use them as well. // an array var names = ["Jerry", "Elaine", "George", "Kramer"]; var alsoNames = new Array("Dennis", "Frank", "Dee", "Mac"); // a round number var roundNumber = Math.round("3.14"); // today's date var today = new Date(); // a boolean object var booleanObject = new Boolean(true); // infinity var unquantifiablyBigNumber = Infinity; // a string object var hello = new String("Hello!"); What are Objects? (Cont…) One thing that you may find strange is the existence of the Object-form of the string, boolean, and number primitives. On the surface, the Object-form and primitive-form of these types look very similar. Here is an example: var movie = "Pulp Fiction"; var movieObj = new String("Pulp Fiction"); alert(movie); alert(movieObj); Output is identical. Below the surface, though, both movie and movieObj are very different. One is literally a primitive of type string, and the other is of type Object. Strings The letters and symbols that make up your language have a formal name. They are known as strings. Strings in JavaScript are nothing more than a series of characters. The Basics: var text = "this is some text"; var moreText = 'I am in single quotes!’; alert("this is some more text"); Besides just listing strings, you’ll often combine a couple of strings together. You can easily do that by just using the + operator: var initial = "hello"; alert(initial + " world!"); alert("I can also " + "do this!"); The only important thing to keep in mind is that you need to wrap your string literals in either quotation marks (") or apostrophes (') to designate them as a region of text String Properties and Methods: Accessing Individual Characters String is a series of characters. You can access each character in several ways. The most common way is by using array/bracket notation and passing in a number that corresponds to the index position of the character: var vowels = "aeiou"; alert(vowels); In this example, we see the i character because it is the item at the second index position. See figure. Index positions in JavaScript start at 0 and move up from there. That is why your index position is 2, but the count of the element at that position is actually 3. String Properties and Methods: Accessing Individual Characters (Cont…) Here is an example of the preceding paragraph in action: var vowels = "aeiou"; for (var i = 0; i < vowels.length; i++) { alert(vowels[i]); } While you may not be looping through a string all the time, it is very common to use the length property to get a count of the number of characters in your string. If you don’t get along with the array/bracket notation, you also have the charAt method that returns a character at a specified index position: var vowels = "aeiou"; alert(vowels.charAt(2)); String Properties and Methods: Combining (Concatenating) Strings To combine two strings together, you can just use the + or += operators and just add them like you would a series of numbers: var stringA = "I am a simple string."; var stringB = "I am a simple string, too!"; alert(stringA + " " + stringB); You can mix and match string literals with string primitives and string objects and still get your text all combined together. For example, this is all valid: var textA = "Please"; var textB = new String("stop!"); var combined = textA + " make it " + textB; alert(combined); The combined variable is simply a string primitive. For combining strings, you also have the concat method. You can call this method from any string and specify a sequence of string primitives, literals, and objects that you want to combine into one…megastring: var foo = "I really"; var blah = "why anybody would"; var blarg = "do this"; var result = foo.concat(" don't know", " ", blah, " ", blarg); alert(result); String Properties and Methods: Making Substrings out of Strings: a. the Slice Method Sometimes, what you are interested in is a sequence of characters somewhere in the middle of your string. The two properties that help satisfy this interest are slice and substr. var theBigString = "Pulp Fiction is an awesome movie!"; The slice method allows you to specify the start and end positions of the part of the string that you want to extract: var theBigString = "Pulp Fiction is an awesome movie!"; alert(theBigString.slice(5, 12)); String Properties and Methods: Making Substrings out of Strings: a. The Slice Method In this example, we extract the characters between index positions 5 and 12. The end result is that the word Fiction is what will get returned. The start and end position values do not have to be positive. If you specify a negative value for the end position, the end position for your string is what is left out when you count backwards from the end: var theBigString = "Pulp Fiction is an awesome movie!"; alert(theBigString.slice(0, -6)); If you specify a negative start position, your start position is the count of whatever you specify starting from the end of the string: var theBigString = "Pulp Fiction is an awesome movie!"; alert(theBigString.slice(-14, -7)); String Properties and Methods: Making Substrings out of Strings: b. The Substr Method substr method. This method takes two arguments as well: var newString = substr(start, length); The first argument is a number that specifies your starting position, and the second argument is a number that specifies the length of your substring. This makes more sense when we look at some examples: var theBigString = "Pulp Fiction is an awesome movie!"; alert(theBigString.substr(0, 4)); // Pulp We start the substring at the zeroth position and count four characters up. That is why Pulp is returned. If you want to just extract the word Fiction, this is what your code would look like: var theBigString = "Pulp Fiction is an awesome movie!"; alert(theBigString.substr(5, 7)); // Fiction If you don’t specify the length, the substring that gets returned is the string that goes from the start position to the end: var theBigString = "Pulp Fiction is an awesome movie!"; alert(theBigString.substr(5)); // Fiction is an awesome movie! String Properties and Methods: Splitting a String/split Calling the split method on a string returns an array of substrings. These substrings are separated by a character or Regular Expression that you use to determine when to split apart your string. Let’s look at a simple example where this makes more sense: var inspirationalQuote = "That which you can concatenate, you can also split apart."; var splitWords = inspirationalQuote.split(" "); alert(splitWords.length); // 10 In this example, we are splitting the inspirationalQuote text on the space character. Every time a space character is encountered, what is left of the string before it is removed and made an item in the array that gets returned by this method. Here is another example: var days = "Monday,Tuesday,Wednesday,Thursday,Friday, Saturday, Sunday"; var splitWords = days.split(","); alert(splitWords); // Sunday String Properties and Methods: Finding Something Inside a String If you ever need to find a character or characters inside a string, you can use the indexOf, lastIndexOf, and match methods. Let’s look at the indexOf method first. What the indexOf method does is take the character(s) you are looking for as its argument. If what you are looking for is found, it returns the index position in the string where the first occurrence…occurs. If no matches are found, this method gifts you with a –1. Let’s look at an example: var question = "it is says life is hard, but life is beautiful too"; alert(question.indexOf("life")); // 11 Because what I am looking for does exist, the indexOf method lets me know that the first occurrence of this word occurs at the 18th index position. If I look for something that doesn’t exist, like the letter z in this example, a –1 gets returned for: var question = "I wonder what the pigs did to make these birds so angry?"; alert(question.indexOf("z")); // -1 String Properties and Methods: Finding Something Inside a String (Cont…) The lastIndexOf method is very similar to indexOf. As you can guess by the name, lastIndexOf returns the last occurrence of what you are looking for: var question = "How much wood could a woodchuck chuck if a woodchuck could chuck wood?"; alert(question.lastIndexOf("wood")); // 65 In addition to providing the characters to search for, you can also specify an index position on your string to start your search from: var question = "How much wood could a woodchuck chuck if a woodchuck could chuck wood?"; alert(question.indexOf("wood", 30)); // 43 String Properties and Methods: Finding Something Inside a String (Cont…) The last thing to mention about the indexOf and lastIndexOf methods is that you can match any instance of these characters appearing in your string. These functions do not differentiate between whole words or what you are looking for being a substring of a larger set of characters. Be sure to take that into account. Before we wrap this up, let’s look at the match method. With the match method, you have a little more control. This method takes a Regex as its argument: var phrase = "There are 3 little pigs."; var regexp = /[0–9]/; var numbers = phrase.match(regexp); alert(numbers); // 3 String Properties and Methods: Upper and Lower Casing Strings To uppercase or lowercase a string, you can use the appropriately named toUpperCase and toLowerCase methods. Let’s look at this example: var phrase = "My name is Bond. James Bond."; alert(phrase.toUpperCase()); // MY NAME IS BOND. JAMES BOND. alert(phrase.toLowerCase()); // my name is bond. james bond. Labs: https://www.w3schools.com/js/js_objects.asp https://www.w3schools.com/js/js_datatypes.asp https://www.w3schools.com/js/js_strings.asp Thank you