# [JavaScript] 擷取字串 substr(), substring(), slice()的區別 ###### tags: `JavaScript` ## 相同點 * 都可以傳入一個或兩個參數 * 只傳入一個參數時,都表示從指定下標,截取字符串長度,直到字符串最後一個字符 ``` var str = ‘hello sarahshine!‘; console.log(str.slice(3)); // ‘lo sarahshine!‘ console.log(str.substring(3)); // ‘lo sarahshine!‘ console.log(str.subtr(3)); // ‘lo sarahshine!‘ ``` ## 不同點 #### 傳入兩個參數時,第二個參數代表的意義不同 * slice ( ) 和 substring ( ) 的第二個參數,都表示截取字符串的結束位置 * substr ( ) 的第二個參數代表的是,要截取的字符串位數 ``` var str = ‘hello sarahshine!‘; console.log(str.slice(3,7)); // ‘lo s‘ console.log(str.substring(3,7)); // ‘lo s‘ console.log(str.substr(3,7)); // ‘lo sara‘ ``` #### 傳入的參數是負數 * slice ( ) 會把所有的負數參數加上字符串的長度值,如:str.slice(-3) 相當於 str.slice(14) * substring ( ) 會把所有的負數參數都轉為0 * substr ( ) 會把第一個參數的負值加上字符串的長度值,第二個參數的負值轉為0 (畢竟第二個參數是要截取的字符串長度,總不能為負數吧) ``` var str = ‘hello sarahshine!‘; //length = 17 //只傳入一個負數 console.log(str.slice(-3)); // ‘ne!‘ 相當於str.slice(14) console.log(str.substring(-3)); // ‘hello sarahshine!‘ 相當於str.substring(0) console.log(str.substr(-3)); // ‘ne!‘ 相當於str.substr(14) //傳入兩個負數 console.log(str.slice(-3, -1)); // ‘ne‘ 相當於str.slice(14,16) console.log(str.substring(-3, -1)); // ‘‘ 相當於str.substring(0,0) console.log(str.substr(-3, -1)); // ‘‘ 相當於str.substr(14,0) //傳入一正一負 console.log(str.slice(3, -4)); // ‘lo sarahsh‘ 相當於str.slice(3,13) console.log(str.substring(3, -4)); // ‘hel‘ 相當於str.substring(3,0) 即(0,3) console.log(str.substr(3, -4)); // ‘‘ 相當於str.substr(3,0) ```