Will'http:url'适用于所有浏览器和设备

Will 'http:url' work for all browsers and devices?

本文关键字:浏览器 url http Will 适用于      更新时间:2023-09-26

在制作一个验证用户URL并在前面加上http:的函数时,我必须将www、https和//视为有效的URL。按照我现在的编写方式(见下文),我只预写了http:,这样//stackoverflow.com的情况就不会变成http://stackoverflow.com/

这意味着像stackoverflow.com这样的url变成了http:stackoverflow.com.

在Firefox和Chrome中,这很好,但可以从各种浏览器和设备中单击这些URLS这是通用的东西吗为//案例重写这张支票很容易,但我对答案很感兴趣。

预处理方法:

function prependHTTPtoWebURL() {
    var url = (el('org_website').value);
    var httpVar;
    var testFor;
    if (url) {// If there's a website URL value
        testFor = url.toLowerCase();
        if (testFor.indexOf("http") != 0){
            httpVar = 'http:'; //add it
            url = httpVar + url;
         el('org_website').value = url;
     }
    }
}

尝试使用regex。例如,检查此代码:

var someurl = "www.google.com";
var otherurl = "google.com";
var anotherurl = "//google.com";
function prependHTTPtoWebURL(url) {
    var newurl = url.replace(/^(http)?(:)?('/'/)?/i,'');
    return 'http://' + newurl;
}
console.log(prependHTTPtoWebURL(someurl));
console.log(prependHTTPtoWebURL(otherurl));
console.log(prependHTTPtoWebURL(anotherurl));

console.log中的输出将为:

http://www.google.com
http://google.com
http://google.com

由于您在第一个子域上指定了一个子域(www),因此这是受尊重的。它避免像http:////那样以四条对角线结尾。如果你的url类似于:google.com,它也会正确修复它。

你可以在这里看到它的直播:http://jsfiddle.net/zRBUj/

编辑:添加凯特提到的/i

将http:更改为http://

查看这些链接了解更多信息:

URL 剖析

网络的工作原理