JavaScript 字串處理

Posted by Adam on August 24, 2022
# 📘 字串處理 ```js var mainString = "Hello, world!"; var subString = "world"; console.log(mainString.length); // 字串長度:13 console.log(subString.length); // 字串長度:5 if (mainString.includes(subString)) { console.log("字串包含指定的子字串"); } else { console.log("字串不包含指定的子字串"); } var sentence = "This is a sample sentence."; var words = sentence.split(" "); // 將句子按空格切割成單字陣列 console.log(words); // ["This", "is", "a", "sample", "sentence."] var originalStr = "Hello, world!"; var subStr1 = originalStr.substring(0, 5); // 從索引 0 到索引 4 的子字串 var subStr2 = originalStr.substr(7, 5); // 從索引 7 開始,取 5 個字元的子字串 console.log(subStr1); // "Hello" console.log(subStr2); // "world" ``` ### 模板字串(Template literals): 使用模板字串可以更清晰地格式化字串,通過在字串周圍使用反引號,全在字串中使用${}來插入變數。例如: ```js var name = "John"; var age = 30; var formattedString = `My name is ${name} and I am ${age} years old.`; console.log(formattedString); ``` --- # 📘 Regex ```js // 將 "world" 替換為 "universe" var str = "Hello, world!"; var newStr = str.replace(/world/, "universe"); // 使用正則表達式進行替換 console.log(newStr); // "Hello, universe!" // 替換所有數字為 "#" var text = "12345 and 67890"; var replacedText = text.replace(/\d/g, "#"); console.log(replacedText); // "##### and #####" // 將 yyyy-mm-dd 格式的日期轉換成 mm/dd/yyyy 格式 var dateStr = "2023-05-25"; var formattedDate = dateStr.replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1"); console.log(formattedDate); // "05/25/2023" // 首字字母大寫,其餘小寫 function format(str) { return str.toLowerCase().replace(/^\w/, (c) => c.toUpperCase()); } ``` 在 JavaScript(以下簡稱 “JS”)裡,正則表示式(RegExp)主要有兩種宣告方式,並搭配一系列常用的標誌(flag)與語法結構。以下分段說明並輔以範例。 一、宣告方式 1. 文字(Literal)語法 let re = /pattern/flags; 範例: ```js const re1 = /\d{3}-\d{4}/g; // 尋找「3 位數字 + ‘-’ + 4 位數字」,全域搜尋 ``` 2. 建構子(Constructor)語法 let re = new RegExp("pattern", "flags"); 範例: ```js const re2 = new RegExp("\\d{3}-\\d{4}", "g"); // 在字串中,\ 要再多加一層跳脫 ``` 二、常用標誌(Flags) - g (global):全域搜尋,不只第一筆 - i (ignore case):不分大小寫 - m (multiline):多行模式,^、$ 可在每行起/尾匹配 - u (unicode):啟用 Unicode 支援(例如 u+{1F601}) - s (dotAll):讓 . 能匹配換行符(\n) - y (sticky):「黏貼」模式,從 lastIndex 精確位置開始匹配 三、核心語法元件與範例 1. 字元類別(Character Classes) - \d:數字等價於 [0-9] - \D:非數字等價於 [^0-9] - \w:英文數字底線 [A-Za-z0-9_] - \W:非 \w - \s:空白字元 [\t\n\r\f\v] - . :除換行以外的任意字元(s 標誌下可包含換行) 範例: ```js /\w+@\w+\.\w{2,3}/i // 電子郵件簡易匹配 ``` 2. 量詞(Quantifiers) - X*:0 次或多次 - X+:1 次或多次 - X?:0 次或 1 次 - X{n}:剛好 n 次 - X{n,}:至少 n 次 - X{n,m}:介於 n–m 次 範例: ```js /a{2,4}/ // "aa", "aaa", "aaaa" 都可 ``` 3. 邊界與定位符(Anchors) - ^:字串或行首 - $:字串或行尾 - \b:單字邊界 - \B:非單字邊界 範例: ```js /^Hello/ // 以 Hello 開頭 /world!$/ // 以 world! 結尾 /\bcat\b/ // 獨立的 "cat" ``` 4. 群組與選擇 - ( … ):括號群組,默認會記錄(capturing group) - (?: … ):非記錄群組(non-capturing) - |:或(alternation) 範例: ```js /(dog|cat)s?/ // dog, dogs, cat, cats /(?:Mr|Mrs)\.?\s[A-Z][a-z]+/ // 非捕獲:Mr. Smith, Mrs Jones ``` 5. 前瞻與後顧(Lookaround) - (?= … ):正向前瞻 - (?! … ):負向前瞻 - (?<= … ):正向後顧 (ES2018+) - (?<! … ):負向後顧 (ES2018+) 範例: ```js /\d+(?=%)/ // 匹配緊跟百分比符號前的數字 /(?<=\$)\d+/ // 匹配美元符號後的數字 ``` 四、常用搭配方法 1. RegExp 物件方法 - test(str):回傳 true/false - exec(str):回傳第一組匹配結果(含群組),無則 null 範例: ```js const re = /cat/g; console.log(re.test("a cat")); // true console.log(re.exec("a cat")); // ["cat", index:2, …] ``` 2. String 物件方法 - match(re):回傳所有匹配(若無 g,則回傳第一組) - replace(re, repl):替換匹配 - search(re):回傳第一個匹配的索引 - split(re):以正則為分隔符拆分字串 範例: ```js "a1b2c3".match(/\d/g); // ["1","2","3"] "foo".replace(/o/g, "0"); // "f00" "hello".search(/l+/); // 2 "a,b;c".split(/[,;]/); // ["a","b","c"] ``` 五、小結 - 宣告:Literal (/…/flags) 或 Constructor - 標誌:g, i, m, u, s, y - 元件:字元類別、量詞、錨點、群組、前瞻/後顧 - 常用方法:test, exec, match, replace, search, split