我正在尝试验证以“http://”或“https://”开头的字符串。一些例子:
http://example.com -> 好
https://example.com -> 好
http:///example.com -> 错误
http://www.example.com -> 错误
https//example.com -> 错误
我有这个正则表达式,但效果不好:
str.match(/^(http|https):\/\/?[a-d]/);
......有什么帮助吗?
我正在尝试验证以“http://”或“https://”开头的字符串。一些例子:
http://example.com -> 好
https://example.com -> 好
http:///example.com -> 错误
http://www.example.com -> 错误
https//example.com -> 错误
我有这个正则表达式,但效果不好:
str.match(/^(http|https):\/\/?[a-d]/);
......有什么帮助吗?
老实说,我不知道为什么人们对每件简单的事情都想要一个正则表达式。如果您需要做的只是比较字符串的开头,那么在某些情况下检查它会更快,例如您所要求的(“验证开头带有单词'http://'的字符串或'https://'"):
var lc = str.toLowerCase();
var isMatch = lc.substr(0, 8) == 'https://' || lc.substr(0, 7) == 'http://';
试试这个
str.match(/^(http(s)?:\/\/)[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/)