将"http://"添加到尚未包含"http://"的URL

Dav*_*vid 41 html javascript variables

我有一个input保存URL 的字段,我希望这个保存的输入能够识别变量开头没有"Http //"但不知道从哪里开始...是否可以只检查一部分一串? - 然后有必要附加的功能?

Mat*_*ley 94

如果你还想允许"https://",我会使用这样的正则表达式:

if (!/^https?:\/\//i.test(url)) {
    url = 'http://' + url;
}
Run Code Online (Sandbox Code Playgroud)

如果你不熟悉正则表达式,这就是每个部分的含义.

  • ^ - 仅匹配字符串的开头
  • http - 匹配文字字符串"http"
  • s? - 可选择匹配"s"
  • : - 匹配冒号
  • \/\/ - 转义"/"字符,因为它们标记正则表达式的开头/结尾
  • 正则表达式之后的"i"使其不区分大小写,因此它将匹配"HTTP://"等.

  • 使用```!/ ^(https?:))?\ /\// i.test(url)```来处理//:example.com. (4认同)
  • 你应该知道 ```!/^https?:\/\//i.test(undefined)``` 是 ```true```。我建议检查 ``url``` 是否不假:````if (!!url && !/^https?:\/\//i.test(url)) {...``` (2认同)
  • 使用答案中的正则表达式,可以编写一行: 'stackoverflow.com'.replace(/^(https?:\/\/)?/i, (a)=>a || 'http: //') (2认同)

Mar*_*ers 68

您想要的简单解决方案如下:

var prefix = 'http://';
if (s.substr(0, prefix.length) !== prefix)
{
    s = prefix + s;
}
Run Code Online (Sandbox Code Playgroud)

但是你应该注意一些事情......

这里的测试区分大小写.这意味着如果字符串最初Http://example.com会将其更改http://Http://example.com为可能不是您想要的字符串.你可能也不应该修改任何字符串,foo://否则你最终会得到类似的东西http://https://example.com.

另一方面,如果你收到一个输入,example.com?redirect=http://othersite.com那么你可能确实想要前置,http://所以只是搜索://可能不够好,不适合一般的解决方案.

替代方法

相关问题

  • 请注意,对于协议相关 URL(以“//”开头的 URL,这可能会产生意外结果。例如:`//example.com/foo`,上面的代码会将其更改为`http:////example.com/foo` (2认同)

qua*_*oup 24

Linkenizer解除(Null不介意)

link = (link.indexOf('://') === -1) ? 'http://' + link : link;
Run Code Online (Sandbox Code Playgroud)

这将预先考虑'http://'link,如果它不能找到://指示协议.如果://在字符串的其他地方出现,这将无法正常工作,但这已经足够了.

例子:

http://www.google.com -> http://www.google.com
ftp://google.com      -> ftp://google.com
www.google.com        -> http://www.google.com
google.com            -> http://google.com
Run Code Online (Sandbox Code Playgroud)

由于您说您正在保存此URL,因此最好在服务器端执行此操作,因此禁用js的客户端不会弄乱链接.

  • 轻微改进:`((link.indexOf('://') === -1) && (link.indexOf('mailto:') === -1) ) ? 'http://' + 链接:链接` (2认同)

Aks*_*yal 6

下面的代码片段检查:

  • 检查 url 是否不为空
  • 删除开头或结尾的杂散空格
  • 检查http://example.comhttps://example.com//example.com

    if (!!url && !!url.trim()) { //Check if url is not blank
        url = url.trim(); //Removes blank spaces from start and end
        if (!/^(https?:)?\/\//i.test(url)) { //Checks for if url doesn't match either of: http://example.com, https://example.com AND //example.com
            url = 'http://' + url; //Prepend http:// to the URL
        }
    } else {
        //Handle empty url
    }
    
    Run Code Online (Sandbox Code Playgroud)


小智 5

这就是我用于即时满足的东西.在jquery中使用keyup监听器.

$('#url').keyup(function () {
        if (  ($(this).val().length >=5) && ($(this).val().substr(0, 5) != 'http:') && ($(this).val().substr(0, 5) != 'https') ) {
            $(this).val('http://' + $(this).val());
        }
    });
Run Code Online (Sandbox Code Playgroud)


小智 5

我将@Mark Byers的答案也更改为也包含“ https://”。

function formatUrl(url){
    var httpString = 'http://'
        , httpsString = 'https://'
        ;

    if (url.substr(0, httpString.length) !== httpString && url.substr(0, httpsString.length) !== httpsString)
        url = httpString + url;

    return url;
}
Run Code Online (Sandbox Code Playgroud)


rap*_*2-h 5

ES6,一根内胆

这是一种“现代”方法:

const withHttp = url => !/^https?:\/\//i.test(url) ? `http://${url}` : url;
Run Code Online (Sandbox Code Playgroud)

您现在可以将其withHttp用作功能:

const myUrl = withHttp("www.example.org");
Run Code Online (Sandbox Code Playgroud)


Cha*_*ngo 5

ES6,一个内胆

const withHttp = (url) => url.replace(/^(?:(.*:)?\/\/)?(.*)/i, (match, schemma, nonSchemmaUrl) => schemma ? match : `http://${nonSchemmaUrl}`);
Run Code Online (Sandbox Code Playgroud)

测试(所有返回http://www.google.com):

  • www.google.com
  • google.com
  • //google.com
  • http://www.google.com
  • https://www.google.com
  • ftp://www.google.com

如果有人需要知道它是如何工作的,请添加评论,我会添加解释。