JS 筆記 | String 操作篇

閱讀時間約 6 分鐘

這是三部曲的最後一篇。不得不說,Leetcode 或一些公司的面試技術考都是在這三部曲上加上各種演算法,嚴格一點的測試還會加上時間複雜度,一不小心一題可能就花了大半的考試時間。

今天的主角是字串 (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: [email protected], [email protected]'

// 不帶 g
const matchedEmail = text.match(/\S+@\S+\.\S+/)
console.log(matchedEmail) // '[email protected],'

// 帶 g
const matchedEmail = text.match(/\S+@\S+\.\S+/g)
console.log(matchedEmail) // ​[ '[email protected],', '[email protected]' ]

// 帶 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 '
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 字串處理函數
18會員
37內容數
這個專題用來存放我在學習網頁開發時的心得及知識。
留言0
查看全部
發表第一個留言支持創作者!