定義正則表達式
如果正則表達式規則不會改變,可以使用斜線的方式定義(寫死)正則表達式,效能較佳:
let regex = /^09\d{8}$/;
^09\d{8}$ 的意思為:
- ^:從開頭處就需要符合
- 0:數字 0
- 9:數字 9
- \d:任何數字
- {8}:重複 8 次
- $:字串結尾
let regex = new RegExp("^09\\d{8}$");
不論是使用上面介紹的兩個斜線(/ /)還是使用 new RegExp 來定義正則表達式,兩者的使用方式相同。
test: 測試是否符合正則表達式,回傳 true/false
let input = '0987654321';
let regex = /^09\d{8}$/;
let result = regex.test(input);
console.log(result); // true
search: 測試是否符合正則表達式,回傳 index(不符合回傳 -1)
字串 "abc123" 中找到 c 的位置,結果為 2 (從 0 開始)
let input = 'abc123';
let regex = /c/;
let result = input.search(regex)
console.log(result); // 2
exec: 找出符合正則表達式的字串,回傳 Array 或是 null
字串 "abc123" 中找到 c 的位置,結果為 2 (從 0 開始)
let input = 'abc123';
let regex = /a/;
let result = input.search(regex)
console.log(result); // ["a"]
文章撰寫中...請稍後...
參考資料:
mdn - Regular expressions
感謝教學~
回覆刪除