0% found this document useful (0 votes)
13 views

23 StringsInJavaScript

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

23 StringsInJavaScript

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Eric Roberts and Jerry Cain Handout #23

CS 106J May 1, 2017


Strings in JavaScript

Early Character Encodings


• The idea of using codes to represent letters dates from before the
Strings in JavaScript time of Herman Hollerith, as described in Chapter 6.
• Most of you are familiar with the work of Samuel F. B. Morse,
inventor of the telegraph, who devised a code consisting of dots
and dashes. This scheme made it easier to transmit messages
and paved the way for later developments in communication.

Eric Roberts and Jerry Cain


CS 106J
May 1, 2017

Samuel Morse (1791-1872) Alphabetic Characters in Morse Code

The Victorian Internet Review: Strings as an Abstract Idea


What you probably don’t know is • Characters are most often used in programming when they are
that the invention of the telegraph combined to form collections of consecutive characters called
also gave rise to many of the social strings.
phenomena we tend to associate with • As you will discover when you have a chance to look more
the modern Internet, including chat closely at the internal structure of memory, strings are stored
rooms, online romances, hackers, internally as a sequence of characters in sequential memory
and entrepreneurs—all of which are addresses.
described in Tom Standage’s 1998
book, The Victorian Internet. • The internal representation, however, is really just an
implementation detail. For most applications, it is best to
think of a string as an abstract conceptual unit rather than as
the characters it contains.
• JavaScript emphasizes the abstract view by defining a built-in
string type that defines high-level operations on string values.

Using Methods in the String Class Selecting Characters from a String


• JavaScript defines many useful methods that operate on • Conceptually, a string is an ordered collection of characters.
strings. Before trying to use those methods individually, it is
important to understand how those methods work at a more • In JavaScript, the character positions in a string are identified
general level. by an index that begins at 0 and extends up to one less than
the length of the string. For example, the characters in the
• Because strings are objects, JavaScript uses the receiver string "hello, world" are arranged like this:
syntax to call string methods. Thus, if str is a string, you
would apply the method name using str.name(arguments). h e l l o , w o r l d
0 1 2 3 4 5 6 7 8 9 10 11
• None of the methods in JavaScript’s String class change the • You can obtain the number of characters by checking the
value of the string used as the receiver. What happens instead length property, as in str.length.
is that these methods return a new string on which the desired
changes have been performed. • You can select an individual character by calling charAt(k),
where k is the index of the desired character. The expression
• Classes that prohibit clients from changing an object’s state
are said to be immutable. Immutable classes have many str.charAt(0);
advantages and play an important role in programming. returns the one-character string "h" that appears at index 0.
–2–

Concatenation Extracting Substrings


• One of the most useful operations available for strings is • The substring method makes it possible to extract a piece of
concatenation, which consists of combining two strings end a larger string by providing index numbers that determine the
to end with no intervening characters. extent of the substring.
• As you know from earlier in the quarter, concatenation is built • The general form of the substring call is
into JavaScript in the form of the + operator.
str.substring(p1, p2);
• It is also important to recall that JavaScript interprets the +
operator as concatenation only if at least one of the operands where p1 is the first index position in the desired substring
is a string. If both operands are numbers, the + operator and p2 is the index position immediately following the last
signifies addition. position in the substring.
• As an example, if you wanted to select the substring "ell"
from a string variable str containing "hello, world" you
would make the following call:

str.substring(1, 4);

Comparing Strings Searching in a String


• JavaScript allows you to call the standard relational operators • The method indexOf takes a string and returns the index
to compare the values of two strings in a natural way. For within the receiver at which the first instance of that string
example, if s1 and s2 are strings, the expression begins. If the string is not found, indexOf returns -1. For
example, if str contains the string "hello, world":
s1 === s2
str.indexOf("h") returns 0
is true if the strings s1 and s2 contain the same characters. str.indexOf("o") returns 4
• String comparisons involving the operators <, <=, >, and >= str.indexOf("ell") returns 1
are implemented in a fashion similar to traditional alphabetic str.indexOf("x") returns -1
ordering: if the first characters match, the comparison
operator checks the second characters, and so on. • The indexOf method takes an optional second argument that
indicates the starting position for the search. Thus:
• Characters are compared numerically using their Unicode
values. For example, "cat" > "CAT" because the character str.indexOf("o", 5) returns 8
code for "c" (99) is greater than the code for "C" (67). This
style of comparison is called lexicographic ordering. • The lastIndexOf method works similarly except that it
searches backward from the end of the receiving string.

Other Methods in the String Class Exercise: Implementing endsWith


String.fromCharCode(code) • The startsWith and endsWith methods did not exist in early
Returns the one-character string whose Unicode value is code. versions of JavaScript. The text includes an implementation
charCodeAt(index) of startsWith written as a client function. How would you
Returns the Unicode value of the character at the specified index. do the same for endsWith?
toLowerCase()
Returns a copy of this string converted to lower case.
toUpperCase()
Returns a copy of this string converted to upper case.
startsWith(prefix)
Returns true if this string starts with prefix.
endsWith(suffix)
Returns true if this string starts with suffix.
trim()
Returns a copy of this string with leading and trailing spaces removed.
–3–

Simple String Idioms Reversing a String


When you work with strings, there are two idiomatic patterns that
are particularly important:
1. Iterating through the characters in a string.
for (var i = 0; i < str.length; i++) {
var ch = str.charAt(i); str result i
. . . code to process each character in turn . . .
}

2. Growing a new string character by character.


var result = "";
for (whatever limits are appropriate to the application) {
. . . code to determine the next character to be added . . .
> reverse("stressed")
result += ch; desserts
} >

Exercise: Implementing toUpperCase The GLabel Class


• Suppose that the toUpperCase method did not exist. How You can display a string in the graphics window using the GLabel
would you implement a toUpperCase function that returns class, as illustrated by the following function that displays the
the same result? string "hello, world" on the graphics window:
function HelloWorld() {
var gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT);
var label = GLabel("hello, world", 100, 75);
label.setFont("SansSerif-36");
label.setColor("Red");
gw.add(label);
}

HelloWorld

hello, world

Operations on the GLabel Class The Geometry of the GLabel Class


Function to create a GLabel • The GLabel class relies on a set of geometrical concepts that
GLabel(text, x, y) are derived from classical typesetting:
Creates a label containing the specified text that begins at the point (x, y). – The baseline is the imaginary line on which the characters rest.
– The origin is the point on the baseline at which the label begins.
Methods specific to the GLabel class – The height of the font is the distance between successive baselines.
label.setFont( font) – The ascent is the distance characters rise above the baseline.
Sets the font used to display the label as specified by the font string.
– The descent is the distance characters drop below the baseline.
The font is typically specified as a string in the form • You can use the getHeight, getAscent, and getDescent
methods to determine the corresponding property of the font.
"family-style-size" You can use the getWidth method to determine the width of
the entire label, which depends on both the font and the text.
where QuickBrownFox

family is the name of a font family origin


style is either PLAIN, BOLD, ITALIC, or BOLDITALIC The quick brown fox jumps ascent

size is an integer indicating the point size height


over the lazy dog. baseline
descent

You might also like