Logo

JavaScript RegExp 常見用法

Dec 23, 2025
20 min read

大學第一次學前端做期末專案時,為了驗證一個 Email 格式,我寫了滿滿的 if-else 去檢查 @ 和點號的位置,結果隨便輸入一個字串還是漏洞百出。後來才知道,那些讓我寫到崩潰的字串判斷,其實只需要一行正規表示式 (Regular Expression) 就能優雅解決。

雖然這串「外星符號」第一眼看起來很嚇人,但是掌握規則後,它就是你處理字串最強大的武器。


什麼是 Regular Expression?

簡單來說,Regular Expression 就是一種定義搜尋模式的語法。你可以把它想像成進階版的「尋找與取代」,用來檢查字串是否符合特定格式。

在 JavaScript 中,建立 RegExp 有兩種方式:

  • 建構函式 (Constructor)
  • 字面值 (Literal)

接著就來看看如何使用這兩種方式來建立 RegExp 吧!


建立 RegExp

使用 Constructor

js
1const regex = new RegExp("cat", 'gi');

使用 Literal

js
1const regex = /cat/gi;

常見 flag 包含:

  • g:global search,全域搜尋
  • i:case-insensitive search,不分大小寫
  • m:multiline,多行模式
  • s:dotAll,使 . 能多 match 換行符號
  • u:啟用 Unicode 模式
  • y:sticky 模式,從 lastIndex 開始比對

注意事項

  • pattern 為固定字面量時,使用 regular expression literal /.../
  • 只有在 pattern 需要動態拼接時,才需使用 constructor new RegExp()

常用的 RegExp 方法與字串方法

RegExp.prototype.test()

回傳是否成功 match

js
1const regex = /cat/i; 2 3console.log(regex.test("My Cat")); // true 4console.log(regex.test("Dog")); // false

常見用途

  • 驗證表單輸入是否符合格式
  • 格式驗證,例如 Email、手機號碼等
  • feature flag / route 判斷

RegExp vs String API

  • includes()startsWith()endsWith() 可取代簡單判斷
  • 若只是「是否包含某字串」,不需要用到 RegExp

RegExp.prototype.exec()

取得 match 到的結果(包含 group 資訊)

js
1const datePattern = /(\d{4})-(\d{2})-(\d{2})/; 2const result = datePattern.exec("Today is 2025-11-14"); 3 4console.log(result[0]); // "2025-11-14" 5console.log(result[1]); // "2025" 6console.log(result[2]); // "11" 7console.log(result[3]); // "14"

常見用途

  • 需要取得 group 資訊的字串解析
  • 搭配 g flag 來逐次擷取結構化資料

RegExp vs String API

  • 無對應 String API
  • exec 是「結構解析」最核心的 RegExp 工具

String.prototype.match()

回傳 match 到的內容

若沒有加 g flag,回傳第一個 match 到的結果。若加上 g flag,則會回傳所有結果:

js
1const input = "cat5566"; 2input.match(/\d/); 3// ["5"] 4 5const input2 = "cat55dog66"; 6input2.match(/\d+/g); 7// ["55", "66"]

常見用途

  • 快速取得第一個 match
  • 或是搭配 g flag 取得所有符合字串

RegExp vs String API

  • 單純搜尋可用 indexOf
  • 需要多筆結果才適合 match(/.../g)

String.prototype.matchAll()

js
1const input = "cat:55.dog:66"; 2[...input.matchAll(/(\w+):(\d+)/g)]; 3// [["cat:55", "cat", "55"], ["dog:66", "dog", "66"]]

matchAll 會回傳一個 RegExpStringIterator,有幾格常見得的用法:

  • next():迭代。
  • value:取值。
  • done:判斷是否已經到最後了。

常見用途

  • 需要多筆 + capture group 的解析結果
  • 比 exec + while 更易讀

RegExp vs String API

  • 無對應 String API
  • 屬於現代 JS 處理結構化字串的推薦方式

String.prototype.replace()

替換字串內容

基本替換:

js
1const input = "cat5566"; 2input.replace(/\d/, "*"); 3// "cat*566"

全域替換:

js
1const id = "123-456-789"; 2id.replace(/\d/g, "*"); 3// "***-***-***"

使用 group 來重組字串:

js
1const date = "2025-11-30"; 2date.replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1"); 3// "30/11/2025"

也能使用 callback 動態生成替換內容:

js
1const input = "cat66"; 2input.replace(/\d+/g, (match) => Number(match) * 2); 3// "cat132"

常見用途

  • 格式清理(空白、符號、mask)
  • 搭配 function 做進階轉換

RegExp vs String API

  • 固定字串取代可用 replaceAll()
  • 規則型取代才使用 RegExp

String.prototype.split()

使用 RegExp 拆分字串

js
1const fruits = "apple,banana;grape"; 2fruits.split(/[,;]/); 3// ["apple", "banana", "grape"]

常見用途

  • 多分隔符字串解析
  • 非結構化輸入資料清洗

RegExp vs String API

  • 單一分隔符用字串即可
  • 多規則分隔再使用 RegExp

常見正規表達式實用範例

數字格式驗證

js
1const number = "12345"; 2/^\d+$/.test(number); // true

簡易版的 email 驗證

js
1const email = "test@example.com"; 2/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); // true

從 URL 取出 domain

js
1const url = "https://www.example.com/page?id=1"; 2const domain = url.match(/https?:\/\/([^\/]+)/)[1]; 3 4console.log(domain); // "www.example.com"

壓縮多個空白成一個空白

js
1const input = "hello world JS"; 2input.replace(/\s+/g, " "); 3// "hello world JS"

常用符號與語法速查表

語法說明
.匹配任意字元(不含換行)
\d數字
\w英數字或底線
\s空白
^開頭
$結尾
*0 次或以上
+1 次或以上
?0 或 1 次
{n}重複 n 次
{n,m}重複 n 到 m 次
(...)群組
[...]字元集合

結論

了解 JavaScript RegExp 的基本語法與常用方法,可以提升處理字串的效率。不論是表單驗證或邏輯判定,都能靠正規表達式達成更簡潔、維護性更高的程式!