How can I add http:// to a URL if no protocol is defined in JavaScript?

Nearpoint picture Nearpoint · Jul 9, 2014 · Viewed 10.4k times · Source

My question is the same as this one, but the correct answers are for PHP, not JavaScript.

How to add http:// if it doesn't exist in the URL

How can I add http:// to the URL if there isn't a http:// or https:// or ftp://?

Example:

addhttp("google.com"); // http://google.com
addhttp("www.google.com"); // http://www.google.com
addhttp("google.com"); // http://google.com
addhttp("ftp://google.com"); // ftp://google.com
addhttp("https://google.com"); // https://google.com
addhttp("http://google.com"); // http://google.com
addhttp("rubbish"); // http://rubbish

Basically, how can this same function using PHP syntax be written using JavaScript? Because when I use the function preg_match it is not defined in JavaScript.

function addhttp($url) {
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

Answer

glortho picture glortho · Jul 9, 2014

Use the same function in JavaScript:

function addhttp(url) {
    if (!/^(?:f|ht)tps?\:\/\//.test(url)) {
        url = "http://" + url;
    }
    return url;
}