【學習筆記】JavaScript 尋找字串的方法:includes/indexOf/search/match
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
Photo by Mick Haupt on Unsplash
在處理資料時,查找字串是一種常見的操作,JavaScript 提供不同的方法來搜索字串。其中,最常用的方法包括:search、indexOf、includes 和 match,能夠辨別字串裡是否有想要查找的文字:
- String.prototype.search( )
- String.prototype.indexOf( )
- String.prototype.match()
- String.prototype.includes()
接下來會比較這四種方法的不同之處,以及使用範例。
- 搜索指定字符串,並返回匹配字串第一個字的索引值
- 若找不到,則返回 -1
- 可支援正則表達式
關於正則表達式的用法,可參考這篇筆記:【學習筆記】JavaScript:Regex 正則表達式。
使用範例:
- 搜索指定字符串,並返回匹配字串第一個字的索引值
- 若沒有找到,則返回 -1
- 第二個參數 position 為選填屬性,代表從哪個 index 找起
- 與 search() 方法類似,差別在於 indexOf() 不支援正則表達式
使用範例:
- 搜索指定字符串,並返回一個或多個與指定值匹配的數組
- 若找不到則返回 null
- 支援正則表達式
使用範例:
- 正規表達式匹配:需注意要加上
g
標誌,才會返回匹配的所有結果
找指定字串:
找大寫字母:
- 找到匹配字串返回 true;否則返回 flase
- 不支援正則表達式
使用範例:
小結
過去曾整理過陣列遍歷的相關筆記:
專案中時常需要去搜尋特定字串,來達成特定目的。翻找筆記時,才發現自己竟然還沒有整理過這幾個 JavaScript 提供的方法的差異。
也藉由這個機會,又好好重新複習正則表達式的一些觀念,雖然很多時候是需要用到的時候再查就好,但果然原生的底子還是基礎中的基礎。
此外,也體驗了最近正夯的 ChatGPT,給一段關鍵字寫出來的文章,差不多就完成了八七分架構,只需要再多補充一些觀念,一篇筆記就熱騰騰的誕生了ಠ_ಠ
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
雖然這項功能方便又快速,結果卻不一定 100% 正確,有時也會出現一些瞎掰的,甚至與事實相差甚遠的回答;因此該如何善用這項工具,辨別結果並實際應用在工作上的開發、測試、寫文件等等,想必是使用者需要學習的課題吧。
Reference