javascript - URL用正则表达式验证,缺少时添加 "http://"

标签 javascript regex

我正在尝试创建一个函数来验证 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/

相关文章:

javascript - 在 JavaScript 中使用 Array.at(index) 而不是 Array[index]

javascript - 固定 AppBar 下的内容

javascript - 如何从 mobx 对象中获取普通对象?

php - 如果我将 lat、lng 作为变量传递, map 会中断

python - 从 URL、RE、python 中提取 Amzon ASIN

objective-c - 使用单词验证正则表达式进行输入字符验证

Javascript Regular Expression 获取大括号之间的内容(里面有大括号)

javascript - jQuery - 选中 CHECK ALL 时取消选中其他复选框

java - 我应该将模式对象声明为静态的吗

javascript - 无法使用正则表达式将索引值放在括号内