DIV CSS 佈局教程網

JavaScript 進階教程(第二課):字串處理技巧與 Cookie 入門
編輯:JavaScript基礎知識     

這一課要學一個很有用也很有趣的主題:Cookie——用來記錄造訪過你網頁的人留下的資訊。有了它,你能記住訪客的姓名,在他再次來訪時給一句熱情的招呼;也能記住客戶端的特性,例如發現對方連線速度很慢,就只送出盡可能少的圖片內容。

只要使用得合理(不要拿它窺探使用者的隱私),Cookie 其實非常實用。但在正式開始之前,我們得先補兩個 JavaScript 基礎:字串處理與陣列。

為什麼非得先學字串處理?因為 Cookie 本身就是字串。要保存訪客資訊,你必須先組出一個特殊的 Cookie 字串;等對方再回來時讀取,又必須對這個字串解碼。要生成與解讀這些字串,就得先理解 JavaScript 的字串運作方式。

如果你還是新手,建議先讀過初級教程第二課。先看個例子:

var normal_monkey = "I am a monkey!<br>";
document.writeln("Normal monkey " + normal_monkey);

var bold_monkey = normal_monkey.bold();
document.writeln("Bold monkey " + bold_monkey);

這裡的宣告:

var bold_monkey = normal_monkey.bold();

等同於:

var bold_monkey = "<b>" + normal_monkey + "</b>";

第一種寫法明顯簡潔得多,它用到了字串物件的 bold() 方法。其他的字串方法還有 indexOf、charAt、substring、split 等,這些都能深入字串的內部結構。先從 indexOf 談起。

indexOf

indexOf 用來找出某段字元在字串中的位置,也就是子字串的起始索引。如果字串裡不含該子字串,indexOf 會回傳 -1。

var the_word = "monkey";

var location_of_m = the_word.indexOf("m");     // 0
var location_of_o = the_word.indexOf("o");     // 1
var location_of_key = the_word.indexOf("key"); // 3
var location_of_y = the_word.indexOf("y");     // 5
var cheeky = the_word.indexOf("q");            // -1

location_of_m 是 0,因為 m 就在字串開頭;location_of_key 是 3,因為子字串 "key" 從 k 開始,而 k 在 monkey 中的位置是 3;cheeky 是 -1,因為 monkey 裡沒有 q。

indexOf 更實用的一種玩法是做輸入驗證:

var the_email = prompt("What's your email address?", "");
var the_at_is_at = the_email.indexOf("@");

if (the_at_is_at == -1)
{
    alert("電子郵件位址必須包含 @ 符號。");
}

這段程式詢問使用者的電子郵件,如果輸入內容裡找不到 @ 就提示格式有誤。當然這只是最粗略的檢查,正式環境該用完整的格式驗證。

charAt

charAt 用來取出字串中某個特定位置的字元:

var the_word = "monkey";

var the_first_letter = the_word.charAt(0);
var the_second_letter = the_word.charAt(1);
var the_last_letter = the_word.charAt(the_word.length - 1);

the_first_letter 是 "m",the_second_letter 是 "o",the_last_letter 是 "y"。

注意這裡用到了 length 屬性,它可以告訴你字串裡有多少個字元。本例中 the_word 是 "monkey",所以 the_word.length 是 6。但千萬不要忘記,字串的第一個字元索引是 0,所以最後一個字元的索引是 length - 1,這也是最後一行要寫 the_word.length - 1 的原因。

索引從 0 開始這件事,是初學階段最容易反覆出錯的地方,寫迴圈時要特別小心。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved