【JavaScript】slice()、substring()、substr()的區別
馬嘉楠 2008-12-16
JavaScript中String 對象的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 沒有對該方法進行標準化,因此盡量少使用該方法。
馬嘉楠
jianan.ma@gmail.com
posted on 2008-12-16 11:00
馬嘉楠 閱讀(2480)
評論(2) 編輯 收藏 所屬分類:
Java Script