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

html, javascript, variables

Solution

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

- Javascript equalsIgnoreCase: case insensitive string comparation

- javascript startswith

- How do I parse a URL into hostname and path in javascript?

Problem

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?

Original source

Related problems