Prepending “http://” to a URL that doesn’t already contain “http://”

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 string
  • http – 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.

Leave a Comment