JavaScript 正則表達式

定義正則表達式

如果正則表達式規則不會改變,可以使用斜線的方式定義(寫死)正則表達式,效能較佳:
    
let regex = /^09\d{8}$/;
    

^09\d{8}$ 的意思為:
  • ^:從開頭處就需要符合
  • 0:數字 0
  • 9:數字 9
  • \d:任何數字
  • {8}:重複 8 次
  • $:字串結尾
也可以使用 RegExp 來動態定義可以改變的正則表達式:
    
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

留言

張貼留言

如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com