javascript - 仅验证 URL 字符串开头的“http://”或“https://”
问题描述
我正在尝试验证以“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://';
推荐阅读
- python - 如何移除模型 Tensorflow Keras 中的特定神经元
- java - 在模拟器上运行的位置服务在真实设备上不起作用
- python - 第 26 行,在 __init__ tk.Tk().__init__(self, *args, **kwargs) 中。TypeError:create() 参数 1 必须是 str 或 None,而不是 App
- python - 如何设计一个返回一个或多个值的python函数
- swift - 如何让 SwiftUI WebView 动态加载 URL?
- angular - 如何测试在 jasmine-karma 的 if 语句中调用了一个函数
- python - 如何在 python 中使用 Azure 函数读取 Azure blob 文件?
- ios - 本地化键中的特殊字符
- kubernetes - kubernetes 中的多个 ingress-nginx 未验证 webhook 不起作用
- html - Buffer.toString("utf16le") 的 HTML DOM 等效项