预先加入“http://”到不包含“http://”的URL。 [英] Prepending "http://" to a URL that doesn't already contain "http://"

查看:266
本文介绍了预先加入“http://”到不包含“http://”的URL。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个保存URL的 input 字段,我希望这个保存的输入能够识别变量开始时Http //何时不存在,但是不知道从哪里开始......是否可以只检查一部分字符串? - 然后有一个函数,如果有必要可以追加?

解决方案

一个简单的解决方案,您需要的是以下内容:

  var prefix ='http://'; 
if(s.substr(0,prefix.length)!==前缀)
{
s = prefix + s;
}

然而,有几件事你应该知道...... p>

这里的测试区分大小写。这意味着如果字符串最初是 Http://example.com ,它会将其更改为 http:// Http://example.com 这可能不是你想要的。你可能也不应该修改任何以 foo:// 开头的字符串,否则你可能会以 http:// https://为例另一方面,如果您收到一个输入,如 example.com?redirect=http:。 $ b < //othersite.com 那么你可能想要在> http:// 之前加上,所以只需搜索:// 对于一般解决方案可能不够好。



其他方法




  • 使用正则表达式:

      if(!s.match (/ ^ [a-zA-Z] +:\ / \ //))
    {
    s ='http://'s;
    }


  • 使用URI解析库,例如 JS-URI

      if(new URI(s).scheme === null)
    {
    s ='http://'s;
    }




相关问题


I have an input field that saves a URL, I'd like this saved input to recognize when "Http//" is absent from the start of the variable but have no idea where to begin... is it possible to check only a portion of a string? - then have a function that will append if necessary?

解决方案

A simple solution for what you want is the following:

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

However there are a few things you should be aware of...

The test here is case-sensitive. This means that if the string is initially Http://example.com this will change it to http://Http://example.com which is probably not what you want. You probably should also not modify any string starting with foo:// otherwise you could end up with something like http://https://example.com.

On the other hand if you receive an input such as example.com?redirect=http://othersite.com then you probably do want to prepend http:// so just searching for :// might not be good enough for a general solution.

Alternative approaches

Related questions

这篇关于预先加入“http://”到不包含“http://”的URL。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆