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?
- 12,731
- 15
- 43
- 51
13 Answers
If you also want to allow "https://", I would use a regular expression like this:
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.
- 98,974
- 24
- 106
- 127
-
You should be aware that ```!/^https?:\/\//i.test(undefined)``` is ```true```. I suggest to check if ```url``` is not falsey: ```if (!!url && !/^https?:\/\//i.test(url)) {...``` – Nikita Hismatov May 12 '17 at 07:14
-
4Use ```!/^(https?:)?\/\//i.test(url)``` to handle //:example.com as well. – Akshay Goyal Jun 12 '17 at 09:47
-
1With the regex in your answer, it's possible to write a one-liner: 'stackoverflow.com'.replace(/^(https?:\/\/)?/i, (a)=>a || 'http://') – brunettdan Oct 14 '19 at 08:28
-
How can we make it avoid FTP urls? – Amante Ninja Jun 23 '20 at 10:29
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
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; }
Related questions
- 1
- 1
- 767,688
- 176
- 1,542
- 1,434
-
-
1Note for protocol relative URLS (urls that start with) `//`, this may have unexpected results. ex: `//example.com/foo`, the code above would change it to `http:////example.com/foo` – Kevin Wheeler Jun 24 '15 at 20:05
Lifted from the Linkenizer (Null won't mind)
link = (link.indexOf('://') === -1) ? 'http://' + link : link;
This will prepend 'http://' to link if it can't find the :// indicating protocol. This won't work well if :// occurs elsewhere in the string, but it's good enough.
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.
- 1
- 1
- 25,753
- 9
- 40
- 57
-
3slight improvement: `((link.indexOf('://') === -1) && (link.indexOf('mailto:') === -1) ) ? 'http://' + link : link` – Prashant May 17 '19 at 12:58
ES6, one liner
Here is a "modern" approach:
const withHttp = url => !/^https?:\/\//i.test(url) ? `http://${url}` : url;
You can now use withHttp as a function:
const myUrl = withHttp("www.example.org");
- 26,857
- 31
- 150
- 246
Here is what I use for instant gratification. utilizing the keyup listener in jquery.
$('#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());
}
});
- 71
- 1
- 1
-
1thanks, used this, just changed the JQuery selector to ```$('input[type=url]')``` – Dirk Jan 29 '16 at 13:14
ES6, one liner
const withHttp = (url) => url.replace(/^(?:(.*:)?\/\/)?(.*)/i, (match, schemma, nonSchemmaUrl) => schemma ? match : `http://${nonSchemmaUrl}`);
Tested for (all return http://www.google.com):
www.google.comgoogle.com//google.comhttp://www.google.comhttps://www.google.comftp://www.google.com
If anyone need to know how it works add a comment and I'll add an explanation.
- 6,654
- 1
- 27
- 37
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.com AND //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 }
- 881
- 9
- 11
-
1You shouldn't return http:// as a default, it's better to just add '//' double forward slashes. – Jimba Tamang Mar 18 '20 at 04:15
I altered @Mark Byers's answer to include "https://" as well.
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;
}
- 51
- 1
- 4
Something like this (writing by memory)?
if (url.toUpper(url.substring(0, 7) != "HTTP://")
url = "http://" + url;
- 44,434
- 7
- 64
- 121
I altered @Morgan Taylor's and @Mark Byer's answers to be case unsensitive. Works with http:// and https://
function formatUrl(url)
{
var httpString = "http://";
var httpsString = "https://";
if (url.substr(0, httpString.length).toLowerCase() !== httpString && url.substr(0, httpsString.length).toLowerCase() !== httpsString)
url = httpString + url;
return url;
}
- 341
- 3
- 6
I personally use this, which is partially taken from php docs
$scheme = parse_url($link, PHP_URL_SCHEME);
if (empty($scheme)) {
$link = 'http://' . ltrim($link, '/');
}
- 732
- 6
- 19
You can use "StartsWith" a member of System.String.
if (url.ToUpper().StartsWith("HTTP://"))
{
}
- 4,191
- 3
- 34
- 55
-
5
-
And, I just knocked up a console app, targeting .net 3.5 and this compiles and builds fine: string url = @"http://msdn.microsoft.com/en-us/library/ms131452(v=VS.90).aspx"; if (url.ToUpper().StartsWith("HTTP://")) { Console.WriteLine("Is this c#, the method is defined in Assembly mscorlib.dll, v2.0.50727."); } – Daniel James Bryars Aug 22 '10 at 20:36
-
@Daniel James Bryars: It seems that "this is not C#" refers to the question, whose tags currently (rev.1) read "javascript html variables" - no C#. – Piskvor left the building Aug 22 '10 at 20:41
-
Late to the game, but JavaScript now has `String.startsWith()` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith – Jimmerz28 Oct 29 '16 at 21:00