If you also want to allow “https://”, I would use a regular expression like this:
if (!/^https?:\/\//i.test(url)) {
url="http://" + url;
}
If you’re not familiar with regular expressions, here’s what each part means.
^– Only match at the beginning of the stringhttp– Match the literal string “http”s?– Optionally match an “s”:– Match a colon\/\/– Escape the “https://stackoverflow.com/” characters since they mark the beginning/end of the regular expression- The “i” after the regular expression makes it case-insensitive so it will match “HTTP://”, etc.