-
Notifications
You must be signed in to change notification settings - Fork 3.3k
第 87 题:在输入框中如何判断输入的是一个正确的网址 #138
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
不上正则,一个简单的玩法 function isUrl(url) {
const a = document.createElement('a')
a.href = url
return [
/^(http|https):$/.test(a.protocol),
a.host,
a.pathname !== url,
a.pathname !== `/${url}`,
].find(x => !x) === undefined
} |
var reg=/^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9- |
可以问一下吗?a.pathname !== |
输入/a 和 输入 a,不算完整网站。但是pathname都是/a |
function isUrl(url) {
try {
new URL(url);
return true;
}catch(err){
return false;
}} |
|
/^(https?:\/\/)?([a-z0-9]\.|[a-z0-9][-a-z0-9]*[a-z0-9]\.)*([a-z]+)(:\d+)?(\/.*)?$/; |
可能还需要检查一下protocol是http|https |
/^(?:(https?):)?(?:\/\/)?([^\/?#:]+)?(?::(\d+))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/ |
what is a URL from MDN
|
let url = 'https://www.baidu.com';
function searchUrl(url) {
try {
if (new URL(url) && (new URL(url).protocol === "http:" || new URL(url).protocol === "https:") && url.match(new RegExp(new URL(url).protocol + "//")).index === 0) return true
} catch (err) {
console.log("不是一个正确的网址");
}
};
console.log(searchUrl(url)) |
stackoverflow上的:
|
@lhyt |
const a = document.createElement('input')
a.type = 'url'
a.value = '..'
a.checkValidity() // false, 不推荐用于精确判断的场景 |
/^(http(s)?://)?([\w-]+.)?[\w-]+.[\w-]+(?[\w-]+=[\w-]+(&[\w-]+=[\w-_]+)*)?$/ |
vue-element-admin 上面的方法 |
这个代码看了我强迫症犯病 |
No description provided.
The text was updated successfully, but these errors were encountered: