7

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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nearpoint
  • 7,202
  • 13
  • 46
  • 74
  • Doesn't matter what language it is, the same logic applies. – Ben Fortune Jul 09 '14 at 15:18
  • The answers there are just using regex. JavaScript has a regex engine. Apply the same logic. – Quentin Jul 09 '14 at 15:18
  • I am not familiar with regex so when I tried to use the code from the duplicate question it did not work in javascript! Javascript does not have a preg_match function. Other questions and answer on this site show how to add http but do not check for other protocols like ftp. The answer defined in php was the best but does not work in javascript and I did not know how to apply the same logic in javascript. – Nearpoint Jul 09 '14 at 15:31
  • 4
    This is not exactly duplicate. The other question is asking 'how to' in PHP. Javascripts short hand regex `/expresion/i` makes it difficult (different) to implement the same expression. I vote to keep this question. – Lex Nov 03 '15 at 08:43

1 Answers1

34

Use the same function in JavaScript:

function addhttp(url) {
    if (!/^(?:f|ht)tps?\:\/\//.test(url)) {
        url = "http://" + url;
    }
    return url;
}
olegtaranenko
  • 3,722
  • 3
  • 26
  • 33
glortho
  • 13,120
  • 8
  • 49
  • 45
  • The function in the other answer had 'preg_match' function which was not available in javascript. And I was not aware of the .test mehtod thanks! – Nearpoint Jul 09 '14 at 15:25
  • 1
    This function fails for protocol-relative URLs, which are pretty common nowadays: `addhttp("//stackoverflow.com") => "http:////stackoverflow.com"` – MCL Jan 05 '23 at 11:50