【JavaScript】slice()、substring()、substr()的區別——dream參考之二

stringObject.slice(startIndex,endIndex)

  返回字符串 stringObject 從 startIndex 開始(包括 startIndex )到 endIndex 結束(不包括 endIndex )爲止的所有字符。

  1)參數 endIndex 可選,如果沒有指定,則默認爲字符串的長度 stringObject.length 。

雙擊代碼全選
1
2
3
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表示字符串最後一個字符。

雙擊代碼全選
1
2
3
4
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)

雙擊代碼全選
1
2
3
var stringObject = "hello world!";
alert(stringObject.slice()); // hello world!
alert(stringObject.slice(0)); // hello world!

  4)如果startIndex、endIndex 相等,則返回空串

  【注3】String.slice() 與 Array.slice() 相似

雙擊代碼全選
1
stringObject.substring(startIndex、endIndex)

  返回字符串 stringObject 從 startIndex 開始(包括 startIndex )到 endIndex 結束(不包括 endIndex )爲止的所有字符。

  1)startIndex 是一個非負的整數,必須填寫。endIndex 是一個非負整數,可選。如果沒有,則默認爲字符串的長度stringObject.length 。

雙擊代碼全選
1
2
3
4
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)

雙擊代碼全選
1
2
3
4
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 。

雙擊代碼全選
1
2
3
4
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 沒有對該方法進行標準化,因此儘量少使用該方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章