RegExp 是 regular expression 的縮寫,也就是正則表達式。它用來描述字串的搜尋模式,常用於比對、驗證、擷取與取代等情境。
基本語法有兩種:
const pattern1 = new RegExp('pattern', 'modifiers');
const pattern2 = /pattern/modifiers;
修飾符常見的有 i 與 g。i 表示不區分大小寫,g 表示全域搜尋。
const str = 'Visit W3CSchool';
const p1 = /w3cschool/i;
const str2 = 'Is this all there is?';
const p2 = /is/g;
const p3 = /is/gi;
方括號通常用來指定字元範圍,例如:
/[abc]/
/[a-z]/
/[^abc]/
元字元是具有特殊意義的字元,例如:
\d // 數字
\w // 單字字元
\s // 空白字元
. // 任意字元
量詞用來描述前一個元素出現的次數:
n+ // 一次或多次
n* // 零次或多次
n? // 零次或一次
n{3} // 剛好三次
RegExp 物件常用方法包含 test() 與 exec()。test() 會回傳是否匹配,exec() 則會回傳比對結果。
字串物件也支援多種正則相關方法,例如 match()、replace()、search() 與 split()。
'Hello world'.match(/world/);
'Please visit Microsoft'.replace('Microsoft', 'W3CSchool');