Javascript 在尚未包含“http://”的 URL 前添加“http://”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3543187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Prepending "http://" to a URL that doesn't already contain "http://"
提问by David
I have an inputfield 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?
我有一个input保存 URL的字段,我希望这个保存的输入能够识别变量开头何时不存在“Http//”但不知道从哪里开始......是否可以只检查一部分一个字符串?- 然后有一个函数可以在必要时追加?
回答by Matthew Crumley
If you also want to allow "https://", I would use a regular expression like this:
如果您还想允许“https://”,我会使用这样的正则表达式:
if (!/^https?:\/\//i.test(url)) {
url = 'http://' + url;
}
If you're not familiar with regular expressions, here's what each part means.
如果您不熟悉正则表达式,下面是每个部分的含义。
^- Only match at the beginning of the stringhttp- Match the literal string "http"s?- Optionally match an "s":- Match a colon\/\/- Escape the "/" characters since they mark the beginning/end of the regular expression- The "i" after the regular expression makes it case-insensitive so it will match "HTTP://", etc.
^- 只匹配字符串的开头http- 匹配文字字符串“http”s?- 可选匹配“s”:- 匹配一个冒号\/\/- 转义“/”字符,因为它们标记了正则表达式的开始/结束- 正则表达式后的“i”使其不区分大小写,因此它将匹配“HTTP://”等。
回答by Mark Byers
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.comthis will change it to http://Http://example.comwhich 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.
这里的测试区分大小写。这意味着如果字符串最初是Http://example.com这将改变它http://Http://example.com可能不是你想要的。您可能也不应该修改任何以开头的字符串,foo://否则最终可能会得到类似http://https://example.com.
On the other hand if you receive an input such as example.com?redirect=http://othersite.comthen you probably do want to prepend http://so just searching for ://might not be good enough for a general solution.
另一方面,如果您收到这样的输入,example.com?redirect=http://othersite.com那么您可能确实想要预先添加,http://因此仅搜索对于://通用解决方案来说可能不够好。
Alternative approaches
替代方法
Using a regular expression:
if (!s.match(/^[a-zA-Z]+:\/\//)) { s = 'http://' + s; }Using a URI parsing library such as JS-URI.
if (new URI(s).scheme === null) { s = 'http://' + s; }
使用正则表达式:
if (!s.match(/^[a-zA-Z]+:\/\//)) { s = 'http://' + s; }使用 URI 解析库,例如JS-URI。
if (new URI(s).scheme === null) { s = 'http://' + s; }
Related questions
相关问题
回答by quantumSoup
Lifted from the Linkenizer(Null won't mind)
从Linkenizer 中解除(Null 不会介意)
link = (link.indexOf('://') === -1) ? 'http://' + link : link;
This will prepend 'http://'to linkif it can't find the ://indicating protocol. This won't work well if ://occurs elsewhere in the string, but it's good enough.
这将预先考虑'http://'到link,如果它不能找到://指示协议。如果://出现在字符串的其他地方,这将无法正常工作,但已经足够了。
Examples:
例子:
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
Since you said you are saving this URL, it would be a better idea to do this on the server-side, so clients who have js disabled won't mess up the links.
既然您说要保存此 URL,那么最好在服务器端执行此操作,这样禁用 js 的客户端就不会弄乱链接。
回答by rap-2-h
ES6, one liner
ES6,一个内胆
Here is a "modern" approach:
这是一种“现代”方法:
const withHttp = url => !/^https?:\/\//i.test(url) ? `http://${url}` : url;
You can now use withHttpas a function:
您现在可以将其withHttp用作函数:
const myUrl = withHttp("www.example.org");
回答by cjpetrus
Here is what I use for instant gratification. utilizing the keyup listener in jquery.
这是我用来即时满足的东西。在 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());
}
});
回答by Morgan Taylor
I altered @Mark Byers's answer to include "https://" as well.
我改变了@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;
}
回答by Akshay Goyal
Below code snippet checks for:
下面的代码片段检查:
- Checks if url is not blank
- Removes stray blank spaces at start or end
Checks for http://example.com, https://example.comAND //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 }
- 检查 url 是否不为空
- 删除开头或结尾的杂散空格
检查http://example.com、https://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 }
回答by Casey Chu
if (url.indexOf('http://') != 0)
url = 'http://' + url;
回答by Eugene Mayevski 'Callback
Something like this (writing by memory)?
像这样的东西(凭记忆写)?
if (url.toUpper(url.substring(0, 7) != "HTTP://")
url = "http://" + url;
回答by Satbir Kira
I personally use this, which is partially taken from php docs
我个人使用这个,它部分取自 php docs
$scheme = parse_url($link, PHP_URL_SCHEME);
if (empty($scheme)) {
$link = 'http://' . ltrim($link, '/');
}

