[教學]常用處理字串的方法
整理系列 - String

前言
每次都會忘記字串、物件、陣列的方法該怎麼使用,於是我決定花些時間記錄下來,以下是常用處理字串的方法。
目錄:
合併:concat()
concat()
方法將一個或多個字串與原字串連接合併,形成一個新的字符串並回傳。意思等同用加號相加,MDN文件強烈建議使用「賦值運算子」也就是(+
, +=
)來代替此方法。
// 語法 | |
// str.concat(str2, [, ...strN]) | |
// str2為待相加的字串 | |
// strN同為待相加的字串,選填 | |
let hello = 'Hello, '; | |
hello.concat('James', '. Have a nice day!') | |
// "Hello, James. Have a nice day!" | |
let list = ['How', ' ', 'are', ' ', 'you.']; | |
''.concat(...list) | |
// "How are you." | |
// 使用展開運算子變成字串 | |
// 各種東西放進來會自動轉型 | |
''.concat({}) // [object Object] | |
''.concat([]) // "" | |
''.concat(null) // "null" | |
''.concat(true) // "true" | |
''.concat(4, 5) // "45" |
分割:split()
split()
方法使用指定的分隔字,將字串分割成子字串,並以陣列的方式回傳。
// 語法 | |
// str.split([separator[, limit]]) | |
// separator為拆分字串的指定字串 | |
// limit為限制回傳數量,選填 | |
let str = 'Hello World'; | |
str.split('') | |
// [H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"] | |
str.split(' ') | |
// ["Hello", "World"] | |
// 需注意 '' 與 ' ' 的不同 | |
str.split('', 4) | |
// ["H", "e", "l", "l"] | |
str.split() | |
// ["Hello World"] | |
// 不放參數就會將字串整個丟進陣列裡 |
分割:substring()
substring()
方法會回傳指定位置之間的字串。
// 語法 | |
// str.substring(indexStart[, indexEnd]) | |
// indexStart為索引位置,從此處開始提取字元 | |
// indexEnd為擷取內容結束的索引位置,選填 | |
let str = 'Wednessday'; | |
str.substring(0, 3) | |
// "Wed" | |
str.substring(3, 0) | |
// "Wed" | |
// indexStart > indexEnd,兩者就會顛倒 | |
str.substring(5, -2) | |
// "Wedne" | |
str.substring(-3, 1) | |
// "W" | |
str.substring(6, NaN) | |
// "Wednes" | |
// 任一數小於0或為NaN,則當作0 | |
str.substring(7, 15) | |
// "day" | |
str.substring(15, 3) | |
// "nessday" | |
// 任一數大於字串長度,則當作字串長度 | |
str.substring(9, 9) | |
// "" | |
// 兩數相等,回傳空字串 |
我們可以運用字串長度的性質來做處理,像是「列出字串的後5位數」等。使用字串長度顯然更輕鬆,因為不需要去記住起始值與最終值,只需扣掉要的長度即可:
// 列出字串的後5位數 | |
let str = 'characters'; | |
str.substring(str.length - 5) | |
// "cters" |
分割:slice()
slice()
方法提取部分字串並以字串的方式回傳。概念像從某個位置切下去。
// 語法 | |
// str.slice(beginIndex[, endIndex]) | |
// beginIndex為索引位置,從此處開始提取字元 | |
// endIndex為擷取內容結束的索引位置,選填 | |
// 以上兩者為負數時會被當作「字串長度 + 該值」 | |
let str = "Last Christmas I gave you my heart"; | |
// 字串長度:34 | |
str.slice(15) | |
// "I gave you my heart" | |
str.slice(15, 20) | |
// "I gav" | |
str.slice(7, -8) | |
// "ristmas I gave you " | |
// 可以想成從第7個字元開始取,取到剩下8個字元為止 | |
str.slice(-15) | |
// "ve you my heart" | |
// 可以想成從倒數第15個字元開始提取 | |
str.slice(-15, -9) | |
// "ve you" | |
// 可以想像成從倒數第15個字元開始提取,直到剩下9個字元為止 | |
str.slice(-7, 30) | |
// "y h" | |
// 可以想像成從倒數第7個字元開始提取,直到提取到索引值為30為止 |
分割:substr()
substr()
方法會回傳一個由指定位置開始算長度的字串。與上方兩者不太相同,擷取字串並非設定以索引值設定頭尾來取,反之,以頭的索引值開始,擷取內容以長度來區分。
// 語法 | |
// str.substr(start[, length]) | |
// start為開始提取字串的索引位置,若為負值則視為「字串長度 + 該值」 | |
// length為可提取的字元數,選填 | |
let str = 'abcdefu'; | |
str.substr(3) | |
// "defu" | |
str.substr(3, 2) | |
// "de" | |
str.substr(-3, 2) | |
// "ef" | |
str.substr(-3, -2) | |
// "" | |
// length為0或負值會回傳空字串 |
找值:indexOf()
indexOf()
方法與其說找值,不如說它能告訴你想要找的值存不存在。存在會回傳該值的第一個索引值;若不存在就會回傳-1,
// 語法 | |
// str.indexOf(searchString, position) | |
// searchString為要尋找的對象 | |
// position為從特定索引值開始找起,選填 | |
let str = 'The weather today is pretty bad.'; | |
str.indexOf('a') | |
// 6 | |
// 只顯示第一個a的index | |
str.indexOf('today') | |
// 12 | |
// 在index=12時找到today | |
str.indexOf('x') | |
// -1 | |
// 找不到值回傳-1 | |
str.indexOf('weather', 2) | |
// 4 | |
// 從index=2開始找起 |
找值:lastIndexOf()
lastIndexOf()
方法與 indexOf()
方法相似,差別只在於 lastIndexOf()
只會回傳鎖定對象最後一次出現的索引值。
// 語法 | |
// str.lastIndexOf(searchValue[, fromIndex]) | |
// searchValue為要尋找的對象 | |
// fromIndex為從特定索引值開始向左找起,選填 | |
let str = 'One is all, All is one.'; | |
str.lastIndexOf('one') | |
// 19 | |
str.lastIndexOf('w') | |
// -1 | |
str.lastIndexOf('is', 10) | |
// 4 | |
str.lastIndexOf('is', 30) | |
// 16 | |
// fromIndex >= 字串長度,就會搜尋整個字串 | |
str.lastIndexOf('is', -1) | |
// -1 | |
// fromIndex < 0,代表fromIndex=0 |
找值:search()
search()
方法與 indexOf()
方法相似,差別在於 search()
方法可以使用正規表達式。
// 語法 | |
// str.search(regexp) | |
// regexp為正規表達式,也可以使用字串 | |
let str = 'What are you supporting in the 2022 FIFA World Cup?'; | |
str.search(/[A-G]/g) | |
// 36 | |
//找大寫A-G,找到F | |
str.search('FIFA') | |
// 36 |
找值:includes()
includes()
方法不能全然說他能找值,只能說它能判斷你要找的值是否有出現,因為它的回傳值是布林。
// 語法 | |
// str.includes(searchString[, position]) | |
// searchString為要搜尋的字串,不能是正規表達式 | |
// position為從特定索引值開始找起,選填 | |
let str = 'Goblin mode'; | |
str.includes('Goblin') | |
// true | |
str.includes('mode', 5) | |
// true |
取代:replace()
replace()
方法能取代特定文字。
// 語法 | |
// str.replace(substr, newSubStr) | |
// substr為被取代者,可以是字串或是正規表達式 | |
// newSubStr為取代者,可以是字串或是函數 | |
let str = "Hi my name is James. And What's your name?" | |
str.replace('Hi', 'Hello') | |
// "Hello my name is James. And What's your name?" | |
str.replace('name', 'nickname') | |
// "Hi my nickname is James. And What's your name?" | |
// 只會取代第一個字 | |
str.replace(/name/g, 'nickname') | |
// "Hi my nickname is James. And What's your nickname?" | |
// /name/g為正規表達式,此處的小寫g代表要替換掉所有的name | |
// 另有replaceAll()的方法,他能取代字串裡所有符合的字,就不多列出來了 |
去除空白:trim()
trim()
方法能夠清除字串兩端的空格(包含tab)。
// 語法 | |
// str.trim() | |
let str = ' SOS '; | |
str.trim() | |
// "SOS" | |
// 另有trimStart(), trimEnd()方法,可分別清除字串前後的空格,就不多列出了 |
轉大寫:toUpperCase()
toUpperCase()
方法能將字串全部轉為大寫,若非字串是會強制轉型(null
、undefined
會報錯 )。
// 語法 | |
// str.toUpperCase() | |
let str = 'adidas'; | |
str.toUpperCase() | |
// "ADIDAS" |
轉小寫:toLowerCase()
toLowerCase()
方法能將字串全部轉為小寫,若非字串是會強制轉型(null
、undefined
會報錯 )。
// 語法 | |
// str.toLowerCase() | |
let str = 'NIKE'; | |
str.toLowerCase() | |
// "nike" |
結語
以上整理了常用的字串方法,接下來幾篇應該是整理陣列、物件的方法。