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 "/" 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…