Prepending "http://" to a URL that doesn't already contain "http://"

JavascriptHtmlVariables

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

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");

Solution 5 - Javascript

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());
        }
    });

Solution 6 - Javascript

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.

Solution 7 - Javascript

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
     }
    

Solution 8 - Javascript

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;
}

Solution 9 - Javascript

Something like this (writing by memory)?

if (url.toUpper(url.substring(0, 7) != "HTTP://")
  url = "http://" + url;

Solution 10 - Javascript

if (url.indexOf('http://') != 0)
    url = 'http://' + url;

Solution 11 - Javascript

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;
}

Solution 12 - Javascript

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

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

Solution 13 - Javascript

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, '/');
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavidView Question on Stackoverflow
Solution 1 - JavascriptMatthew CrumleyView Answer on Stackoverflow
Solution 2 - JavascriptMark ByersView Answer on Stackoverflow
Solution 3 - JavascriptquantumSoupView Answer on Stackoverflow
Solution 4 - Javascriptrap-2-hView Answer on Stackoverflow
Solution 5 - JavascriptcjpetrusView Answer on Stackoverflow
Solution 6 - JavascriptChangoView Answer on Stackoverflow
Solution 7 - JavascriptAkshay GoyalView Answer on Stackoverflow
Solution 8 - JavascriptMorgan TaylorView Answer on Stackoverflow
Solution 9 - JavascriptEugene Mayevski 'CallbackView Answer on Stackoverflow
Solution 10 - JavascriptCasey ChuView Answer on Stackoverflow
Solution 11 - JavascriptEdo PlantingaView Answer on Stackoverflow
Solution 12 - JavascriptDaniel James BryarsView Answer on Stackoverflow
Solution 13 - JavascriptSatbir KiraView Answer on Stackoverflow