我知道这是一个很常见的问题&有这么多的答案,但我的问题是不同的,我想接受以下所有格式的网址:
http://www.sample.com
https://www.sample.com
http://www.sample.com/xyz
www.sample.com
www.sample.com/xyz/#/xyz
sample.com
// & much more ...
所以这里的想法是,我允许用户进入那里的网站&另一个用户只需点击已保存的网站&去用户网站。因此,限制用户输入正确的URL并不是一个好主意,他们可以输入上述任何格式。这是我正在使用的正则表达式,但它只检查URL是否从正确的协议开始:
^(ftp|http|https):\/\/[^ "]+$
答案 0 :(得分:20)
使用正则表达式^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+\.[a-z]+(\/[a-zA-Z0-9#]+\/?)*$
这是我刚才建立的基本版本。谷歌搜索可以为您提供更多。
这里
/
var a=["http://www.sample.com","https://www.sample.com/","https://www.sample.com#","http://www.sample.com/xyz","http://www.sample.com/#xyz","www.sample.com","www.sample.com/xyz/#/xyz","sample.com","sample.com?name=foo","http://www.sample.com#xyz","http://www.sample.c"];
var re=/^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+(\.[a-z]{2,}){1,3}(#?\/?[a-zA-Z0-9#]+)*\/?(\?[a-zA-Z0-9-_]+=[a-zA-Z0-9-%]+&?)?$/;
a.map(x=>console.log(x+" => "+re.test(x)));

答案 1 :(得分:4)
你可以试试这个:
^((ftp|http|https):\/\/)?(www.)?(?!.*(ftp|http|https|www.))[a-zA-Z0-9_-]+(\.[a-zA-Z]+)+((\/)[\w#]+)*(\/\w+\?[a-zA-Z0-9_]+=\w+(&[a-zA-Z0-9_]+=\w+)*)?$
const regex = /^((ftp|http|https):\/\/)?(www.)?(?!.*(ftp|http|https|www.))[a-zA-Z0-9_-]+(\.[a-zA-Z]+)+((\/)[\w#]+)*(\/\w+\?[a-zA-Z0-9_]+=\w+(&[a-zA-Z0-9_]+=\w+)*)?$/gm;
const str = `http://www.sample.com
https://www.sample.com
http://www.sample.com/xyz
www.sample.com
www.sample.com/xyz/#/xyz
sample.com
www.sample.com
mofiz.com
kolim.com
www.murikhao.www.sample.com
http://murihao.www.sample.com
http://www.sample.com/xyz?abc=dkd&p=q&c=2
www.sample.gov.bd
www.sample.com.en
www.sample.vu
`;
let m;
while ((m = regex.exec(str)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
console.log("matched :"+m[0]);
}