# 關鍵字搜尋功能如何實作 ###### tags: `JavaScript` `JS 直播班 - 2021 秋季班` #### match() 介紹 ([參考連結](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/String/match)): > 1. match() 函式可以用來做字串的比對,分析關鍵字是否存在於字串當中。 > 2. 它是根據「[正規表達式](https://5xruby.tw/posts/15min-regular-expression)」來進行實作的,有興趣的同學可以上網 Google,這邊就不詳細介紹正規表達式的運作方式。 > 3. 「關鍵字」可以是中 / 英文。如果關鍵字存在,則 match() 會回傳一個包含那個關鍵字的陣列; 如果關鍵字不存在,則 match() 會回傳 null。 > 4. 注意,關鍵字在字串中必須是「連續的」,像是以下範例的 keywordSeparate 就會回傳 null。 範例: ```js= // 想要用來比對的字串 let str = "我是 HexSchool 的大帥哥"; /// 以下為 4 種關鍵字 let keywordChinese = "大帥哥"; let keywordEnglish = "HexSch"; let keywordNull = "不存在"; let keywordSeparate = "大哥"; console.log(str.match(keywordChinese)); // 回傳 ["大帥哥"] console.log(str.match(keywordEnglish)); // 回傳 ["HexSch"] console.log(str.match(keywordNull)); // 回傳 null console.log(str.match(keywordSeparate)); // 回傳 null ``` ### 教學開始 (請搭配 [解答](https://codepen.io/znlcgmgk/pen/KKaoNxL?editors=1011) 觀看) #### 步驟一: 取得 input 的文字內容,並使用 trim()、toLowerCase() 做字串處理 > 1. .trim() 可以移除字串首尾的空白,避免發生錯誤; > 2. .toLowerCase() 可以把英文字母都轉成小寫,建議要比對的字串、關鍵字都做這項處理,這樣不管輸入的關鍵字英文字母大小寫為何,都能找到相符合的產品。 #### 步驟二: 搭配 filter() 做篩選 (JS 第 50 - 53 行) > 1. 設定「產品的標題」為欲比對的字串。 > 2. 設定 filter() 的 return 條件為「match() 的回傳值」。如果關鍵字存在,則 match() 會回傳一個陣列; 如果關鍵字不存在,則 match() 會回傳 null。 > 3. 在 JS 中,陣列為真值,會被轉換為 true; null 假值,會被轉換為 false ([參考連結](https://developer.mozilla.org/zh-CN/docs/Glossary/Truthy)) ### 自己練習的codepen [連結](https://codepen.io/binlandz123/pen/ZEXOVMw?editors=1011)