Skip to main content

String (字串) 基本操作

先建立一個字串

let intro = 'My name is Jeremy'

那些跟陣列一樣的處理方法

  1. slice:裁切字串。
  2. concat:合併字串。
  3. indexOf:索引位置查詢。

分割成陣列

  1. split,很常用到的方法,跟陣列轉字串的 join 方法類似,都需要傳入一個分隔符號。split 還可以帶入第二個參數,就是要切割的長度。
// 不帶分隔符號​
const arrIntro = intro.split()
console.log(arrIntro) // [ 'My name is Jeremy' ]

// 不帶空格
const arrIntro = intro.split('')
console.log(arrIntro)
// ['M', 'y', ' ', 'n', 'a', m', 'e', ' ', 'i', 's', ' ', 'J', 'e', 'r', 'e', 'm', 'y']

// 帶空格
const arrIntro = intro.split(' ')
console.log(arrIntro) // [ 'My', 'name', 'is', 'Jeremy' ]

// 不帶空格,帶 length 參數
const arrIntro = intro.split('', 2)
console.log(arrIntro) // [ 'M', 'y' ]​

搜尋與篩選

  1. charAt,尋找索引位置上的字符。
console.log(intro.charAt(0)) // M
  1. substring,可以看做是 charAt 複數版,可以返回一段較長的字串。
console.log(intro.substring(0, 7)) // My name
  1. substr,跟 substring 很像,但第二個參數帶入的是要返回的長度。
console.log(intro.substr(0, 7)) // My name
  1. match,返回字串中有相符的內容。因為只會回傳第一個相符的內容,所以可以在第二個參數代入 g 來回傳所有相符結果,也可以代入 i 來忽略大小寫差異。
建立複雜一點的字串
const text = 'Emails: john@example.com, jane@example.com'
match
// 不帶 g
const matchedEmail = text.match(/\S+@\S+\.\S+/)
console.log(matchedEmail) // 'john@example.com,'

// 帶 g
const matchedEmail = text.match(/\S+@\S+\.\S+/g)
console.log(matchedEmail) // ​[ 'john@example.com,', 'jane@example.com' ]

// 帶 i 和 g
const matchedEmail = text.match(/e/ig)
console.log(matchedEmail) // [ 'E', 'e', 'e', 'e', 'e', 'e' ]
  1. search,跟 match 類似,不同的是會回傳找到的字串位置。
const index = intro.search(/name/)
console.log(index) // 3
  1. startsWithendsWith,用來判斷字串是否帶有特定前後綴。
console.log(intro.startsWith('My')) //true
console.log(intro.endsWith('Jeremy')) // true

置換

  1. replace,顧名思義,就是換掉內容。
const newIntro = intro.replace('Jeremy', 'Joanna')
console.log(newIntro) // My name is Joanna

空白裁切

  1. trim,這個方法在做網頁搜尋功能時會用到,目的是刪除字串首尾的空白。
先創個帶空白的字串
let intro = ' My name is Jeremy '
trim
const newIntro = intro.trim()
console.log(newIntro) // 'My name is Jeremy'

切換大小寫

  1. toUpperCasetoLowerCase,會把整個字串都變成大寫或小寫。
const newIntro = intro.toUpperCase()
console.log(newIntro) // MY NAME IS JEREMY

const newIntro = intro.toLowerCase()
console.log(newIntro) // my name is jeremy

參考資料

  1. JavaScript String 字串處理函數