Skip to main content

獲得子字串 slice

基本使用#

陣列也有 slice 這個 method,都是拿來取得某一段子元素,使用方式為:

str.slice(起始位置,終止位置(不包含))

這邊值得注意的是最後取得的字串不包含終止位置,假設是 slice(0, 5),實際上拿到的就會是 str[0]+str[1]+...+str[4]

let str = 'abcdefg'
console.log(str.slice(0, 5)) // 從 index 0 ~ 4,所以是 abcde

如果你是要從某個 index 一路拿到結尾,那第二個參數可以省略,例如說:

let str = 'abcdefg'
console.log(str.slice(2)) // 從 index 2 拿到最後,所以是 cdefg

簡單來說,如果你想要取 a ~ b 個字,那就是 str.slice(a, b+1)

如果你想從 a 開始取 len 個字元,那就是:str.slice(a, a + len)

// 取 1 ~ 3 個字元
console.log('012345'.slice(1, 4)) // 123
// 從第 2 個開始取 3 個字
console.log('012345'.slice(2, 5)) // 234