title: How can I add http:// to a URL if no protocol is defined in JavaScript?
body: <p>My question is the same as this one, but the correct answers are for PHP, not JavaScript.</p>
  <p><em><a href="https://stackoverflow.com/questions/2762061/how-to-add-http-if-its-not-exists-in-the-url">How to add http:// if it doesn&#39;t exist in the URL</a></em></p>
  <p>How can I add http:// to the URL if there isn't a <em>http://</em> or <em>https://</em> or <em>ftp://</em>?</p>
  <pre><code>Example:
  
  addhttp(&quot;google.com&quot;); // http://google.com
  addhttp(&quot;www.google.com&quot;); // http://www.google.com
  addhttp(&quot;google.com&quot;); // http://google.com
  addhttp(&quot;ftp://google.com&quot;); // ftp://google.com
  addhttp(&quot;https://google.com&quot;); // https://google.com
  addhttp(&quot;http://google.com&quot;); // http://google.com
  addhttp(&quot;rubbish&quot;); // http://rubbish
  </code></pre>
  <p>Basically, how can this same function using PHP syntax be written using JavaScript? Because when I use the function <em>preg_match</em> it is not defined in JavaScript.</p>
  <pre><code>function addhttp($url) {
      if (!preg_match(&quot;~^(?:f|ht)tps?://~i&quot;, $url)) {
          $url = &quot;http://&quot; . $url;
      }
      return $url;
  }
  </code></pre>