2009年9月24日 星期四

【JavaScript】slice()、substring()、substr()的區別

stringObject.slice(startIndex,endIndex)
  返回字串 stringObject 從 startIndex 開始(包括 startIndex )到 endIndex 結束(不包括 endIndex )為止的所有字元。
  1)參數 endIndex 可選,如果沒有指定,則預設為字串的長度 stringObject.length 。
 var stringObject = "hello world!";
 alert(stringObject.slice(3)); // lo world!
 alert(stringObject.slice(3,stringObject.length)); // lo world!
  【注1】字串中第一個字元的位置是從【0】開始的,最後一個字元的位置為【stringObject.length-1】,所以slice()方法返回的字串不包括endIndex位置的字元。
  2)startIndex 、endIndex 可以是負數。如果為負,則表示從字串尾部開始算起。即-1表示字串最後一個字元。
 var stringObject = "hello world!";
 alert(stringObject.slice(-3)); // ld!
 alert(stringObject.slice(-3,stringObject.length)); // ld!
 alert(stringObject.slice(-3,-1)); // ld
  【注2】合理運用負數可以簡化代碼
  3)startIndex、endIndex 都是可選的,如果都不填則返回字串 stringObject 的全部,等同於slice(0)
 var stringObject = "hello world!";
 alert(stringObject.slice()); // hello world!
 alert(stringObject.slice(0)); // hello world!
  4)如果startIndex、endIndex 相等,則返回空串
  【注3】String.slice() 與 Array.slice() 相似
stringObject.substring(startIndex、endIndex)
  返回字串 stringObject 從 startIndex 開始(包括 startIndex )到 endIndex 結束(不包括 endIndex )為止的所有字元。
  1)startIndex 是一個非負的整數,必須填寫。endIndex 是一個非負整數,可選。如果沒有,則預設為字串的長度stringObject.length 。
 var stringObject = "hello world!";
 alert(stringObject.substring(3)); // lo world!
 alert(stringObject.substring(3,stringObject.length)); // lo world!
 alert(stringObject.substring(3,7)); // lo w,空格也算在內[l][o][ ][w]
  2)如果startIndex、endIndex 相等,則返回空串。如果startIndex 比 endIndex 大,則提取子串之前,調換兩個參數。即stringObject.substring(startIndex,endIndex)等同於stringObject.substring(endIndex,startIndex)
 var stringObject = "hello world!";
 alert(stringObject.substring(3,3)); // 空串
 alert(stringObject.substring(3,7)); // lo w
 alert(stringObject.substring(7,3)); // lo w
  【注4】與substring()相比,slice()更靈活,可以接收負參數。
  stringObject.substr(startIndex,length)
  返回字串 stringObject 從 startIndex 開始(包括 startIndex )指定數目(length)的字元字元。
  1)startIndex 必須填寫,可以是負數。如果為負,則表示從字串尾部開始算起。即-1表示字串最後一個字元。
  2)參數 length 可選,如果沒有指定,則預設為字串的長度 stringObject.length 。
 var stringObject = "hello world!";
 alert(stringObject.substr(3)); // lo world!
 alert(stringObject.substr(3,stringObject.length)); // lo world!
 alert(stringObject.substr(3,4)); // lo w
  3)substr()可以代替slice()和substring()來使用,從上面代碼看出 stringObject.substr(3,4) 等同於stringObject.substring(3,7)
  【注5】ECMAscript 沒有對該方法進行標準化,因此儘量少使用該方法。

沒有留言:

wibiya widget