JavaScript學習筆記(1)字符串方法

字符串方法

  • length 屬性返回字符串的長度
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
  • indexOf() 方法返回字符串中指定文本首次出現的索引(位置):
  • lastIndexOf() 方法返回指定文本在字符串中最後一次出現的索引:
  • 如果未找到文本, indexOf() 和 lastIndexOf() 均返回 -1。
var str = "The full name of China is the People's Republic of China.";
var pos = str.indexOf("China");

var str = "The full name of China is the People's Republic of China.";
var pos = str.lastIndexOf("China");
  • 兩種方法都接受作爲檢索起始位置的第二個參數。
var str = "The full name of China is the People's Republic of China.";
var pos = str.indexOf("China", 18);

var str = "The full name of China is the People's Republic of China.";
var pos = str.lastIndexOf("China", 50);
  • search() 方法搜索特定值的字符串,並返回匹配的位置:
var str = "The full name of China is the People's Republic of China.";
var pos = str.search("locate");

提取部分字符串
有三種提取部分字符串的方法:

slice(start, end)
substring(start, end)
substr(start, length)

slice() 方法
slice() 提取字符串的某個部分並在新字符串中返回被提取的部分。
該方法設置兩個參數:起始索引(開始位置),終止索引(結束位置)。
這個例子裁剪字符串中位置 7 到位置 13 的片段:

實例

var str = "Apple, Banana, Mango";
var res = str.slice(7,13);
res 的結果是:Banana

如果某個參數爲負,則從字符串的結尾開始計數。
這個例子裁剪字符串中位置 -12 到位置 -6 的片段:

實例

var str = "Apple, Banana, Mango";
var res = str.slice(-13,-7);

如果省略第二個參數,則該方法將裁剪字符串的剩餘部分:
實例
var res = str.slice(7);

或者從結尾計數:
實例
var res = str.slice(-13);
  • substring() 方法
    substring() 類似於 slice()。
    不同之處在於 substring() 無法接受負的索引。

  • substr() 方法
    substr() 類似於 slice()。
    不同之處在於第二個參數規定被提取部分的長度。

  • 替換字符串內容
    replace() 方法用另一個值替換在字符串中指定的值:

實例

str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3School");

默認地,replace() 只替換首個匹配
默認地,replace() 對大小寫敏感。

  • 轉換爲大寫和小寫
    通過 toUpperCase() 把字符串轉換爲大寫:
    通過 toLowerCase() 把字符串轉換爲小寫:
    實例
var text1 = "Hello World!";       // 字符串
var text2 = text1.toUpperCase();  // text2 是被轉換爲大寫的 text1
  • concat() 方法
    concat() 連接兩個或多個字符串:
    實例
    和+實際上是等效的
var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2);
  • String.trim()
    trim() 方法刪除字符串兩端的空白符:
var str = "       Hello World!        ";
alert(str.trim());

charAt() 方法
charAt() 方法返回字符串中指定下標(位置)的字符串:
charCodeAt() 方法
charCodeAt() 方法返回字符串中指定索引的字符 unicode 編碼:

實例

var str = "HELLO WORLD";
str.charAt(0);            // 返回 H

var str = "HELLO WORLD";

str.charCodeAt(0);         // 返回 72
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章