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

1

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;
}
Internee answered 9/7, 2014 at 15:14 Comment(4)
Doesn't matter what language it is, the same logic applies.Densmore
The answers there are just using regex. JavaScript has a regex engine. Apply the same logic.Cauthen
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.Internee
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.Samhita
S
34

Use the same function in JavaScript:

function addhttp(url) {
    if (!/^(?:f|ht)tps?\:\/\//.test(url)) {
        url = "http://" + url;
    }
    return url;
}
Shimmer answered 9/7, 2014 at 15:19 Comment(2)
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!Internee
This function fails for protocol-relative URLs, which are pretty common nowadays: addhttp("//stackoverflow.com") => "http:////stackoverflow.com"Purulent

© 2022 - 2024 — McMap. All rights reserved.