使用正則表示式報錯 not a function
阿新 • • 發佈:2020-08-28
------------恢復內容開始------------
錯誤形式:
會報 reg.test is not a function一.
var reg = "/^[1-9]$|(^[1-9][0-9]$)|(^[1-9][0-9][0-9]$)|(^[1-9][0-9][0-9][0-9]$)|(^[1-6][0-5][0-5][0-3][0-5]$)/"
正確形式var reg =/^[1-9]$|(^[1-9][0-9]$)|(^[1-9][0-9][0-9]$)|(^[1-9][0-9][0-9][0-9]$)|(^[1-6][0-5][0-5][0-3][0-5]$)/
原因:
1.定義變數規則不要帶引號,會錯誤的!!!
2.如果不使用test,使用match則可以帶引號
二.
var num = 3
console.log(typeof (num)) // number
console.log((list.port).match(eport)) 報錯:(list.port).match is not a function
原因:正則表示式判斷型別必須為string型別,若為其他型別,無法判斷
解決辦法:將number型別轉換為string型別
list.port=(list.port).toString() console.log(typeof (num)) // string console.log((list.port).match(eport)) //無報錯,成功解決問題------------恢復內容結束------------