gpt4 book ai didi

javascript - 修改用于验证 URL 的正则表达式以允许 IP 地址

转载 作者:行者123 更新时间:2023-11-29 18:27:46 25 4
gpt4 key购买 nike

一位为我工作的开发人员编写了一个正则表达式,用于在用户输入 url 时检查有效 url。到目前为止它工作得很好,除了它不能识别 IP 地址这一事实。

url = url.match(/(http\:\/\/)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\S*)?/)

正确:

Given: http://www.mywebsite.com/index.cfm?do=something
Result: http://www.mywebsite.com/index.cfm?do=something

不正确:

Given: http://64.200.10.50/index.cfm?do=something
Result: http://index.cfm?do=something

Should be: http://64.200.10.50/index.cfm?do=something

我如何修改正则表达式以同时考虑 IP 地址?

谢谢

最佳答案

简单的解决方案:只允许除/和 https://与第一个/之间的空格之外的所有内容。这样你也将支持单级域名、ipv6 地址等

/^https?\:\/\/[^\/\s]+(\/.*)?$/

关于javascript - 修改用于验证 URL 的正则表达式以允许 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11348878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com