[英]Javascript: check if an url is valid and starts with “http//” or “https://”
I want to test my urls validity , which should start with http:// or https:// , 我想测试我的网址有效性,该网址应以http://或https://开头,
i ve used this RegExp : 我用过这个RegExp :
private testIfValidURL(str) {
const pattern = new RegExp('^(https?:\\/\\/)?' + // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
'(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator
return !!pattern.test(str);
}
This would work , execpt one case : 这将工作,执行一种情况:
To consider it as valid , my urls should always start with http://
or https://
, but with my function , urls like www.abcd.com
would be treated as valid urls which is not enough for me. 要认为它是有效的,我的网址应始终以
http://
或https://
开头,但是使用我的函数,像www.abcd.com
这样的网址将被视为有效的网址,这对我来说还不够。
Sugesstions ? 嫌疑人?
Just change ^(https?:\\\\/\\\\/)?'
只需更改
^(https?:\\\\/\\\\/)?'
to ^(https?:\\\\/\\\\/)'
, the ?
到
^(https?:\\\\/\\\\/)'
时, ?
means that you want to match zero or one occurnece of a pattern. 表示您要匹配零个或一个出现的模式。 You actually want exactly one occurence, so don't use
?
您实际上只想发生一种情况,所以不要使用
?
:) :)
From regular-expressions : 从正则表达式中 :
?
? - Makes the preceding item optional.
-使上一项为可选。 Greedy, so the optional item is included in the match if possible.
贪婪,因此可选项目包括在比赛中(如果可能)。
You can remove the (...)?
您可以删除
(...)?
chars, so it will be mandatory to have a http or https sequence first. 字符,因此必须先具有http或https序列。
function testIfValidURL(str) { const pattern = new RegExp('^https?:\\\\/\\\\/' + // protocol '((([az\\\\d]([az\\\\d-]*[az\\\\d])*)\\\\.)+[az]{2,}|' + // domain name '((\\\\d{1,3}\\\\.){3}\\\\d{1,3}))' + // OR ip (v4) address '(\\\\:\\\\d+)?(\\\\/[-az\\\\d%_.~+]*)*' + // port and path '(\\\\?[;&a-z\\\\d%_.~+=-]*)?' + // query string '(\\\\#[-az\\\\d_]*)?$', 'i'); // fragment locator return !!pattern.test(str); } console.log(testIfValidURL('www.abcd.com')); console.log(testIfValidURL('http://www.abcd.com')); console.log(testIfValidURL('https://www.abcd.com')); console.log(testIfValidURL('htt://www.abcd.com'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.