有人有用于验证网址的正则表达式(不是用于在文本段落中查找它们)吗? JavaScript 片段将是首选。
在接受的答案中bobince说得对:仅验证方案名称、://、空格和双引号通常就足够了。以下是如何在 JavaScript 中实现验证:
var url = 'http://www.google.com';
var valid = /^(ftp|http|https):\/\/[^ "]+$/.test(url);
// true
或
var r = /^(ftp|http|https):\/\/[^ "]+$/;
r.test('http://www.goo le.com');
// false
或
var url = 'http:www.google.com';
var r = new RegExp(/^(ftp|http|https):\/\/[^ "]+$/);
r.test(url);
// false
语法参考:
实际的 URL 语法非常复杂,并且不容易用正则表达式表示。大多数看起来简单的正则表达式都会给出许多误报和误报。看看有趣这些努力但最终结果也不好。
此外,现在您通常希望允许 IRI 以及老式 URI,因此我们可以链接到有效地址,例如:
http://en.wikipedia.org/wiki/Þ
http://例え.テスト/
我只会进行简单的检查:它是否以已知的良好方法开始:名称?是否不含空格和双引号?如果是这样,那么地狱,它可能已经足够好了。
尝试这个正则表达式
/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
它最适合我。
我在这方面取得了一些成功:
/^((ftp|http|https):\/\/)?www\.([A-z]+)\.([A-z]{2,})/
这显然并不完美,但它很好地处理了我的案件
这个正则表达式是来自 @Aamir 答案的补丁,对我有用
/((?:(?:http?|ftp)[s]*:\/\/)?[a-z0-9-%\/\&=?\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?)/gi
它匹配这些 URL 格式
您可以在输入中简单地使用
type="url"
,然后在js中使用checkValidity()
进行检查
例如:
你的.html
<input id="foo" type="url">
你的.js
$("#foo").on("keyup", function() {
if (this.checkValidity()) {
// The url is valid
} else {
// The url is invalid
}
});
<html>
<head>
<title>URL</title>
<script type="text/javascript">
function validate() {
var url = document.getElementById("url").value;
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
if (pattern.test(url)) {
alert("Url is valid");
return true;
}
alert("Url is not valid!");
return false;
}
</script>
</head>
<body>
URL :
<input type="text" name="url" id="url" />
<input type="submit" value="Check" onclick="validate();" />
</body>
</html>
经过长时间的研究,我构建了这个reg表达式。我希望它也能帮助其他人......
url = 'https://google.co.in';
var re = /[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/;
if (!re.test(url)) {
alert("url error");
return false;
}else{
alert('success')
}
试试这个,它对我有用:
/^(http[s]?:\/\/){0,1}(w{3,3}\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/;
我找不到最适合我的需求的。撰写并发布@ https://gist.github.com/geoffreyrobichaux/0a7774b424703b6c0fffad309ab0ad0a
function validURL(s) {
var regexp = /^(ftp|http|https|chrome|:\/\/|\.|@){2,}(localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\S*:\w*@)*([a-zA-Z]|(\d{1,3}|\.){7}){1,}(\w|\.{2,}|\.[a-zA-Z]{2,3}|\/|\?|&|:\d|@|=|\/|\(.*\)|#|-|%)*$/gum
return regexp.test(s);
}
试试这个正则表达式,它对我有用:
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
return regexp.test(s);
}
尝试一下:
var RegExp =/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i;
/(?:http[s]?\/\/)?(?:[\w\-]+(?::[\w\-]+)?@)?(?:[\w\-]+\.)+(?:[a-z]{2,4})(?::[0-9]+)?(?:\/[\w\-\.%]+)*(?:\?(?:[\w\-\.%]+=[\w\-\.%!]+&?)+)?(#\w+\-\.%!)?/
我使用 /^[a-z]+:[^:]+$/i 正则表达式进行 URL 验证。请参阅我的带有 URL 验证的跨浏览器 InputKeyFilter 代码示例。
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Input Key Filter Test</title>
<meta name="author" content="Andrej Hristoliubov [email protected]">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<!-- For compatibility of IE browser with audio element in the beep() function.
https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css">
<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>
<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>
</head>
<body>
URL:
<input type="url" id="Url" value=":"/>
<script>
CreateUrlFilter("Url", function(event){//onChange event
inputKeyFilter.RemoveMyTooltip();
var elementNewInteger = document.getElementById("NewUrl");
elementNewInteger.innerHTML = this.value;
}
//onblur event. Use this function if you want set focus to the input element again if input value is NaN. (empty or invalid)
, function(event){ this.ikf.customFilter(this); }
);
</script>
New URL: <span id="NewUrl"></span>
</body>
</html>
另请参阅我的页面输入键过滤器的示例。
/^(http|ftp)s?:\/\/((?=.{3,253}$)(localhost|(([^ ]){1,63}\.[^ ]+)))$/
说明:
http
/ ftp
s
可以遵循,但不一定://
是之后必须要做的http://a.b
)和最大值 253localhost
或 domain-name.TLD
。
域名可以由多个标签组成,用 dot
分隔(即 https://inner.sub.domain.net
),
每个标签的最大长度为63。
我没有看到任何地方对 TLD 长度有限制,所以我没有设置任何限制。@bobince 的回答是一个真正令人担忧的问题。
最新的答案非常接近(感谢@Akseli),但他们都错过了URL和长度中的强制性
dot
。
我上面提供的答案也涉及这些。
进一步阅读:
来自 https://www.freecodecamp.org/news/how-to-validate-urls-in-javascript/
function isValidHttpUrl(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_]*)?$', // fragment locator
'i'
);
return pattern.test(str);
}
console.log(isValidHttpUrl('https://www.freecodecamp.org/')); // true
console.log(isValidHttpUrl('mailto://freecodecamp.org')); // false
console.log(isValidHttpUrl('freeCodeCamp')); // false
我尝试了一些,但出现了一些问题,所以我想出了这个。
/(https?:\/\/(?:www\d*\.|(?!www\d*\.))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\d*\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\d*\.|(?!www\d*\.))[a-zA-Z0-9]+\.[^\s]{2,}|www\d*\.[a-zA-Z0-9]+\.[^\s]{2,})/gi;
使用方法
const isValidUrl = (url = '') => {
if (url) {
var expression =
/(https?:\/\/(?:www\d*\.|(?!www\d*\.))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\d*\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\d*\.|(?!www\d*\.))[a-zA-Z0-9]+\.[^\s]{2,}|www\d*\.[a-zA-Z0-9]+\.[^\s]{2,})/gi;
var regex = new RegExp(expression);
return !!url.match(regex);
}
return false;
};
故障
/(
https?:\/\/ # matches http:// or https://
(?:www\d*\.|(?!www\d*\.) # matches an optional "www" prefix with zero or more digits, followed by a dot,
# or excludes "www" prefix followed by digits
)[a-zA-Z0-9][a-zA-Z0-9-]+ # matches the domain name
[a-zA-Z0-9]\. # matches the dot before the top-level domain
[^\s]{2,} # matches the rest of the URL after the domain name
| # or
www\d*\.[a-zA-Z0-9][a-zA-Z0-9-]+ # matches the "www" prefix with zero or more digits, followed by a dot, and the domain name
[a-zA-Z0-9]\. # matches the dot before the top-level domain
[^\s]{2,} # matches the rest of the URL after the domain name
| # or
https?:\/\/ # matches http:// or https://
(?:www\d*\.|(?!www\d*\.) # matches an optional "www" prefix with zero or more digits, followed by a dot,
# or excludes "www" prefix followed by digits
)[a-zA-Z0-9]+\.[^\s]{2,} # matches the domain name and top-level domain
| # or
www\d*\.[a-zA-Z0-9]+\.[^\s]{2,} # matches the "www" prefix with zero or more digits, followed by a dot, and the domain name and top-level domain
)/gi;
有效网址
http://www.example.com
https://www.example.co.uk
http://www1.example.com
http://www2.example.com
http://www3.example.com
https://www1.example.co.uk
https://www2.example.co.uk
https://www3.example.co.uk
https://example.com
http://example.com
www.example.com
www1.example.com
www2.example.com
www3.example.com
www.example.co.uk
www1.example.co.uk
www2.example.co.uk
www3.example.co.uk
无效网址
example
example.com
ftp://example.com
ftp://www.example.com
http://www.example
http://www.example.
http://www.example/
http://example./com
仅使用 javascript 的力量,在某些情况下一个好的方法是使用
let urlToValidate = `${decodeURIComponent(url)}`
const isValidUrl = (url = '') => {
try {
new URL(url);
return true;
} catch (error) {
return false;
}
};
let result = isValidUrl(urlToValidate)
console.log(result)