Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 928
Nearpoint Avatar asked Jul 09 '14 15:07

Nearpoint


1 Answers

Use the same function in JavaScript:

function addhttp(url) {
    if (!/^(?:f|ht)tps?\:\/\//.test(url)) {
        url = "http://" + url;
    }
    return url;
}
like image 179
glortho Avatar answered Oct 17 '22 08:10

glortho