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

Viewed 55541

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?

13 Answers

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

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.

You can avoid regexes (and consequently another problem) by using new URL():

function newURL(string) {
  let url;
  try {
    url = new URL(string);

    if (!url.hostname) {
      // cases where the hostname was not identified
      // ex: user:password@www.example.com, example.com:8000
      url = new URL("https://" + string);
    }
  } catch (error) {
    url = new URL("https://" + string);
  }

  return url;
}

const url = newURL('google.com');

console.log(url); // "https://google.com/"

It works for any string, see the package https://www.npmjs.com/package/new-url

Related