Tải bản đầy đủ - 0 (trang)
Strings: measuring length and extracting parts

Strings: measuring length and extracting parts

Tải bản đầy đủ - 0trang

var someChars = cityToCheck.slice(2);



The slice begins with the index-2 (the third) character, "s". Since no cutoff at the end is

specified, the slice ends with the last character of the string. someChars is "ston".

Now we have a way to capitalize the first character of a string and insure that the

remaining letters are lower-case.

1

2

3

4

5



var firstChar = cityToCheck.slice(0, 1);

var otherChars = cityToCheck.slice(1);

firstChar = firstChar.toUpperCase();

otherChars = otherChars.toLowerCase();

var cappedCity = firstChar + otherChars;



Here's what happens in the code above, line-by-line:

1. Copies the first character of the string and assigns it to the variable firstChar.

2. Copies all the characters from the second one to the end and assigns them to the variable

otherChars.

3. Caps the first character.

4. Lower-cases the other characters.

5. Concatenates both parts to re-form the whole string.

Sometimes it's useful to know how many characters are in a string. For example, suppose

you want to slice the first three characters from any string than exceeds three characters in

length, for example, slicing "Nov" from "November". To find the number of characters in a

string, you use the same language you've already learned to find the number of elements in an

array.

1

2

3

4

5



var month = prompt("Enter a month");

var charsInMonth = month.length;

if (charsInMonth > 3) {

monthAbbrev = month.slice(0, 3);

}



Line 2 counts the characters in the string and assigns the number to the variable

charsInMonth.

Being able to measure the number of characters in a string can come in handy. For

example, suppose you want to loop through a string, checking to see if it has any double spaces

in it. You can use the character count as the loop limiter. Here's some code that checks for

double spaces in a string and displays an alert if they're found.

1 var str = prompt("Enter some text");

2 var numChars = str.length;

3 for (var i = 0; i < numChars; i++) {

4

if (str.slice(i, i + 2) === " ") {

5

alert("No double spaces!");

6

break;



74



7

}

8 }



Line 2 counts the number of characters in the string and assigns the number to the variable

numChars. In line 3, this number is used as the loop limiter. The loop continues to run only as

long as the counter, i, is less than the number of characters in the string. (Remember, the length

is 1-based, and the counter is 0-based, so the loop has to stop 1 short of the length number.)

Line 4 moves through the string character-by-character, examining each 2-character segment,

looking for double spaces.



75



Find the interactive coding exercises for this chapter at:

http://www.ASmarterWayToLearn.com/js/22.html



76



23

Strings:

Finding segments

The New Yorker magazine doesn't allow the phrase "World War II. " They say it should

be "the Second World War." So let's search the following sentence for the banned characters

and replace them with the phrase that the New Yorker prefers.

It is startling to think that, even in the darkest depths of World War II, J. R. R. Tolkien was

writing the trilogy, which contains, with the weird applicability available only to poetry and

myth, the essential notion that the good gray wizard can understand the evil magi precisely

because he is just enough like them to grasp their minds and motives in ways that they cannot

grasp his.

You already know a way to find the banned segment and replace it. Suppose the

paragraph above has been assigned to the variable text.

1 for (var i = 0; i < text.length; i++) {

2

if (text.slice(i, i + 12) === "World War II") {

3

text = text.slice(0, i) + "the Second World War" + text.slice(i + 12);

4

}

5 }



The code loops through the string looking for "World War II." Line 2 progresses through

the string character-by-character, examining each 12-character sequence. If it finds "World

War II," line 3 concatenates three segments: all the characters preceding "World War II," the

substitute phrase "the Second World War," and then all the characters following "World War

II."

But JavaScript has a more efficient way to accomplish this, using the indexOf method.

var firstChar = text.indexOf("World War II");



If the segment exists, the method finds the index of the first character of the segment and

assigns it to the variable firstChar. If the segment doesn't exist, the method assigns -1 to the

variable, so you know it's not there.

Now we can replace the banned phrase with the preferred phrase with less coding.

1 var firstChar = text.indexOf("World War II");

2 if (firstChar !== -1) {

3

text = text.slice(0, firstChar) + "the Second World War" + text.slice(firstChar + 12);

4 {



Line 1 checks for the phrase, assigning the index of the first character of the phrase to the

variable firstChar—if the phrase is found. If it isn't found, -1 is assigned to the variable. If

77



the variable doesn't have the value -1 (line 2)—if the phrase has been found—the

concatenation in line 3 replaces the offending phrase with the correct pharse.

The indexOf method finds only the first instance of the segment you're looking for. In the

example above, you could overcome this limitation by looping. You'd change the first instance

of "World War II" to "the Second World War," then in the next loop iteration, find the next

surviving instance and change that, and so on.

To find the last instance of a segment in a string, use lastIndexOf. The following code

finds the index of the first character of the last instance of the segment, the second "be". The

variable segIndex winds up with a value of 16, the index of "b" in the second "be".

1 var text = "To be or not to be.";

2 var segIndex = text.lastIndexOf("be");



78



Find the interactive coding exercises for this chapter at:

http://www.ASmarterWayToLearn.com/js/23.html



79



24

Strings:

Finding a character at a location

The user has entered his first name. The string has been assigned to the variable

firstName. You want to extract the first character. You already know one way to do it.

var firstChar = firstName.slice(0, 1);



Here's an alternate way to do it that's more direct.

var firstChar = firstName.charAt(0)



The code above finds a single character at index-0 (the beginning) of the string

represented by the variable firstName and assigns it to the variable firstChar.

The following code finds the last character in the string.

var lastChar = name.charAt(name.length - 1);



The following code cycles through a string looking for an exclamation point. If the

character is found, an alert displays.

1 for (var i = 0; i < text.length; i++) {

2

if (text.charAt(i) === "!") {

3

alert("Exclamation point found!");

4

break;

5

}

6 }



Note: The indexOf method can only identify the character at a particular location. It can't

change the character at a location.



80



Find the interactive coding exercises for this chapter at:

http://www.ASmarterWayToLearn.com/js/24.html



81



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Strings: measuring length and extracting parts

Tải bản đầy đủ ngay(0 tr)

×