55

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?

David
  • 12,731
  • 15
  • 43
  • 51

13 Answers13

118

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 string
  • http - 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.
Matthew Crumley
  • 98,974
  • 24
  • 106
  • 127
79

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

Community
  • 1
  • 1
Mark Byers
  • 767,688
  • 176
  • 1,542
  • 1,434
37

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.

Community
  • 1
  • 1
quantumSoup
  • 25,753
  • 9
  • 40
  • 57
  • 3
    slight improvement: `((link.indexOf('://') === -1) && (link.indexOf('mailto:') === -1) ) ? 'http://' + link : link` – Prashant May 17 '19 at 12:58
23

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");
rap-2-h
  • 26,857
  • 31
  • 150
  • 246
7

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());
        }
    });
cjpetrus
  • 71
  • 1
  • 1
  • 1
    thanks, used this, just changed the JQuery selector to ```$('input[type=url]')``` – Dirk Jan 29 '16 at 13:14
7

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.com
  • google.com
  • //google.com
  • http://www.google.com
  • https://www.google.com
  • ftp://www.google.com

If anyone need to know how it works add a comment and I'll add an explanation.

Chango
  • 6,654
  • 1
  • 27
  • 37
6

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
    }
    
Akshay Goyal
  • 881
  • 9
  • 11
5

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;
}
Morgan Taylor
  • 51
  • 1
  • 4
2

Something like this (writing by memory)?

if (url.toUpper(url.substring(0, 7) != "HTTP://")
  url = "http://" + url;
Eugene Mayevski 'Callback
  • 44,434
  • 7
  • 64
  • 121
2
if (url.indexOf('http://') != 0)
    url = 'http://' + url;
Casey Chu
  • 24,085
  • 10
  • 39
  • 59
0

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;
}
Edo Plantinga
  • 341
  • 3
  • 6
-1

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, '/');
}
Satbir Kira
  • 732
  • 6
  • 19
-1

You can use "StartsWith" a member of System.String.

if (url.ToUpper().StartsWith("HTTP://"))
{ 

}
Daniel James Bryars
  • 4,191
  • 3
  • 34
  • 55
  • 5
    if (isNotC#) { return "StartWith does not exist."; } – Hello71 Aug 22 '10 at 20:28
  • 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