我正在尝试创建一个函数来验证 url 正则表达式, 如果同时缺少,请添加“http://”。 我对 Javascript 和编码很陌生,下面的大部分代码 是我遵循的 Youtube 教程。
但是我想添加一个函数来在缺少“http://”之前添加它, 因为使用当前的正则表达式,“www.google.com”和“http://www.google.com” 已验证。问题是当我实际点击访问该网站时, 那些在开始时没有“http://”的保存,不会进入该站点。
function validateForm(siteName, siteUrl) {
if(!siteName || !siteUrl) {
alert('Please fill in the form');
return false;
}
var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var result = siteUrl.search(new RegExp(/^http:\/\//i));
if(!siteUrl.match(regex)) {
alert('Please use a valid URL');
return false;
}
else if(siteUrl.match(regex) && !result) {
siteUrl = "http://" + siteUrl
return true;
}
else {
return true;
}
}
最佳答案
您可以使用 .indexOf()
字符串方法判断http://
是否在字符串的开头。但是,如果 URL 需要 https://
,您可能会遇到前缀 http://
的问题。
else if(siteUrl.match(regex) && !result) {
// Check to see if the string starts with "http://"
// indexOf() returns the index position of the supplied
// string argument within the string.
if(siteUrl.indexOf("http://") !== 0){
siteUrl = "http://" + siteUrl
}
return true;
}
此外(正如@m_callens 在下面的评论中指出的那样),您的 siteUrl
变量是一个函数参数,因此您将无法从函数外部访问它。相反,你根本不应该将它传递给函数,而只是在更高的范围内声明它:
var siteUrl = // Code that initializes the variable
function validateForm(siteName) {
if(!siteName || !siteUrl) {
alert('Please fill in the form');
return false;
}
var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var result = siteUrl.search(new RegExp(/^http:\/\//i));
if(!siteUrl.match(regex)) {
alert('Please use a valid URL');
return false;
}
else if(siteUrl.match(regex) && !result) {
// Check to see if the string starts with "http://"
// indexOf() returns the index position of the supplied
// string argument within the string.
if(siteUrl.indexOf("http://") !== 0){
siteUrl = "http://" + siteUrl
}
}
else {
return true;
}
}
关于javascript - URL用正则表达式验证,缺少时添加 "http://",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42229596/