有用的字符串方法

現在我們已經了解了字符串的基礎知識,讓我們開始思考我們可以使用內置方法對字符串執行哪些有用的操作,例如查找文本字符串的長度,連接和拆分字符串 ,將字符串中的一個字符替換為另一個字符,等等。

先備知識: 基礎的電腦素養、基本的HTML和CSS、以及清楚什麼是JavaScript。
目標: 了解字串是物件,學習使用一些能夠應用這些字串的基礎方法。

把字串當作物件

我們曾經說過,現在我們重申一遍—在 javascript 中,一切東西都可以被當作物件。例如我們創建一個字串。

js
var string = "This is my string";

你的變數成為一個字串的實體物件,因此它將有許多性質(properties)與功能(methods)可以使用。

你的變數成為一個字串的實體物件,因此它將有許多性質(properties)與功能(methods)可以使用。你可以到 String 物件頁面的左方列表查看這些性質與功能!

**好的,在你腦袋燒壞之前先別擔心!**在這趟學習旅程中,關於這些大部分對於現在的你其實還不需要知道。不過有一些你可能會經常使用,我們將在這裡介紹。

Let's enter some examples into a fresh console. We've provided one below (you can also open this console in a separate tab or window, or use the browser developer console if you'd prefer).

找出字串的長度(length)

這很簡單,你可以用 length 屬性。試著輸入下面幾行:

js
var browserType = "mozilla";
browserType.length;

結果應該會回傳數字 7,因為 "mozilla" 字元長度是 7。 這在很多狀況下很好用,舉例來說:你會想知道序列的長度,這樣才能將這些序列按照長度排序,或是讓使用者知道他們輸入的名稱是否太長。

取得字串中的特定字元(string character)

On a related note, you can return any character inside a string by using square bracket notation — this means you include square brackets ([]) on the end of your variable name. Inside the square brackets you include the number of the character you want to return, so for example to retrieve the first letter you'd do this:

js
browserType[0];

記得電腦計數從 0 開始,不是 1! 如果要在任何一個字串中取得最後一個字元,我們可以使用以下程式碼,結合了取得字元的技巧和上面學過的長度屬性:

js
browserType[browserType.length - 1];

"mozilla" 這個詞的長度是 7,但因為電腦是從 0 開始計數,所以最後一個位置是 6,因此我們會將 length-1 。你也可以試試用這個方法找各序列的第一個字母,並將這些序列按字母順序排好 。

尋找字串中的子字串(substring)並提出子字串

  1. Sometim 有時候你會想搜尋是否有一個較小的字串存在於比較大的字串中(我們通常會說是否有個子字串存在於字串中)。這可以用 indexOf() 方法,當中需要一個參數( parameter ),也就是你想搜尋的子字串:
    js
    browserType.indexOf("zilla");
    
    結果會傳回 2,因為子字串 "zilla" 在 "mozilla" 中是從位置 2 開始的。(依然要記得電腦計數是從 0 開始)。這個方法可以用篩選字串,舉例來說:我們有一串網址的清單,而我們只想印出那些包含 "mozilla" 的網址。
  2. This can be done in another way, which is possibly even more effective. Try the following:
    js
    browserType.indexOf("vanilla");
    
    This should give you a result of -1 — this is returned when the substring, in this case 'vanilla', is not found in the main string. You could use this to find all instances of strings that don't contain the substring 'mozilla', or do, if you use the negation operator, as shown below. You could do something like this:
    js
    if (browserType.indexOf("mozilla") !== -1) {
      // do stuff with the string
    }
    
  3. When you know where a substring starts inside a string, and you know at which character you want it to end, slice() can be used to extract it. Try the following:
    js
    browserType.slice(0, 3);
    
    This returns "moz" — the first parameter is the character position to start extracting at, and the second parameter is the character position after the last one to be extracted. So the slice happens from the first position, up to, but not including, the last position. In this example, since the starting index is 0, the second parameter is equal to the length of the string being returned.
  4. Also, if you know that you want to extract all of the remaining characters in a string after a certain character, you don't have to include the second parameter! Instead, you only need to include the character position from where you want to extract the remaining characters in a string. Try the following:
    js
    browserType.slice(2);
    
    This returns "zilla" — this is because the character position of 2 is the letter z, and because you didn't include a second parameter, the substring that was returned was all of the remaining characters in the string.

備註:The second parameter of slice() is optional: if you don't include it, the slice ends at the end of the original string. There are other options too; study the slice() page to see what else you can find out.

改變大小寫

The string methods toLowerCase() and toUpperCase() take a string and convert all the characters to lower- or uppercase, respectively. This can be useful for example if you want to normalize all user-entered data before storing it in a database.

Let's try entering the following lines to see what happens:

js
var radData = "My NaMe Is MuD";
radData.toLowerCase();
radData.toUpperCase();

更動部分字串

You can replace one substring inside a string with another substring using the replace() method. This works very simply at a basic level, although there are some advanced things you can do with it that we won't go into yet.

It takes two parameters — the string you want to replace, and the string you want to replace it with. Try this example:

js
browserType.replace("moz", "van");

Note that to actually get the updated value reflected in the browserType variable in a real program, you'd have to set the variable value to be the result of the operation; it doesn't just update the substring value automatically. So you'd have to actually write this: browserType = browserType.replace('moz','van');

Active learning examples

In this section we'll get you to try your hand at writing some string manipulation code. In each exercise below, we have an array of strings, and a loop that processes each value in the array and displays it in a bulleted list. You don't need to understand arrays or loops right now — these will be explained in future articles. All you need to do in each case is write the code that will output the strings in the format that we want them in.

Each example comes with a "Reset" button, which you can use to reset the code if you make a mistake and can't get it working again, and a "Show solution" button you can press to see a potential answer if you get really stuck.

Filtering greeting messages

In the first exercise we'll start you off simple — we have an array of greeting card messages, but we want to sort them to list just the Christmas messages. We want you to fill in a conditional test inside the if( ... ) structure, to test each string and only print it in the list if it is a Christmas message.

  1. First think about how you could test whether the message in each case is a Christmas message. What string is present in all of those messages, and what method could you use to test whether it is present?
  2. You'll then need to write a conditional test of the form operand1 operator operand2. Is the thing on the left equal to the thing on the right? Or in this case, does the method call on the left return the result on the right?
  3. Hint: In this case it is probably more useful to test whether the method call isn't equal to a certain result.

Fixing capitalization

In this exercise we have the names of cities in the United Kingdom, but the capitalization is all messed up. We want you to change them so that they are all lower case, except for a capital first letter. A good way to do this is to:

  1. Convert the whole of the string contained in the input variable to lower case and store it in a new variable.
  2. Grab the first letter of the string in this new variable and store it in another variable.
  3. Using this latest variable as a substring, replace the first letter of the lowercase string with the first letter of the lowercase string changed to upper case. Store the result of this replace procedure in another new variable.
  4. Change the value of the result variable to equal to the final result, not the input.

備註:A hint — the parameters of the string methods don't have to be string literals; they can also be variables, or even variables with a method being invoked on them.

Making new strings from old parts

In this last exercise, the array contains a bunch of strings containing information about train stations in the North of England. The strings are data items that contain the three-letter station code, followed by some machine-readable data, followed by a semicolon, followed by the human-readable station name. For example:

MAN675847583748sjt567654;Manchester Piccadilly

We want to extract the station code and name, and put them together in a string with the following structure:

MAN: Manchester Piccadilly

We'd recommend doing it like this:

  1. Extract the three-letter station code and store it in a new variable.
  2. Find the character index number of the semicolon.
  3. Extract the human-readable station name using the semicolon character index number as a reference point, and store it in a new variable.
  4. Concatenate the two new variables and a string literal to make the final string.
  5. Change the value of the result variable to equal to the final string, not the input.

結語

不可否認當網站在跟人們互相溝通時,處理文字和句子在程式設計中是相當重要的,尤其是在 JavaScript 中。這篇文章已經傳授你如何去處理字串的方法,應該對以後深入了解其他更複雜主題的你會很有幫助。接下來,我們將會看看最後一個近期內我們需要關注的主要的資料型態 — 陣列。