[英]Validate URL only "http://" or "https://" at the beginning of the string
我正在嘗試驗證以“http://”或“https://”開頭的字符串。 一些例子:
http://example.com -> 好
https://example.com -> 好
http:///example.com -> 錯誤
http:/www.example.com -> 錯誤
https//example.com -> 錯誤
我有這個正則表達式,但效果不佳:
str.match(/^(http|https):\/\/?[a-d]/);
...有什么幫助嗎?
試試這個
str.match(/^(http(s)?:\/\/)[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/)
老實說,我不知道人們為什么要為每件簡單的事情都使用正則表達式。 如果您需要做的只是比較字符串的開頭,那么在某些情況下檢查它會快得多,例如您所要求的(“在開頭使用單詞 'http://' 驗證字符串或“https://”):
var lc = str.toLowerCase();
var isMatch = lc.substr(0, 8) == 'https://' || lc.substr(0, 7) == 'http://';
我不確定 URL 規范,但這應該可以根據您的要求工作。
const URL_REGEX = /^(http|https):\/\/([az]*\.)?[az]*\.[az]{2,}(\/)?$/;
尾部斜杠后的任何內容都會使 URL 無效。
https://example.com/
有效。
https://example.com/path/to/page
無效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.