1

I want to prepand http:// to every URL that doesn't begin with it, I used this:

if (val.search('http://') === -1) {
    val = 'http://' + val;  
}

The problem is that it appends http:// to URLs that begin with https//
I want to ignore both http:// and https://.

gdoron
  • 147,333
  • 58
  • 291
  • 367
user1339164
  • 357
  • 1
  • 5
  • 11
  • Try the 3rd response of this post https://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links That's ok for me – Stephane G. Aug 10 '17 at 11:21

2 Answers2

8
if (val.indexOf('http://') === -1 && val.indexOf('https://') === -1) {
    val = 'http://' + val;
}

The regex way is:

if (!val.search(/^http[s]?:\/\//)){
    val = 'http://' + val;        
}
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • The `[]` is not necessary for a single character; neither is the `g` modifier – ThiefMaster May 18 '12 at 09:43
  • 1
    @ThiefMaster. You're right about the `g` I removed it a sec after I edited, but the `[]` makes it a lot more readable (IMO). don't you think so? – gdoron May 18 '12 at 09:44
  • This could be improved a slight bit by adding the `i` modifier so that the search is not case-sensitive. – bladnman Nov 26 '13 at 14:53
  • @bladnman, it only improve if you really need that modifier otherwise it cost you time and CPU for no good reason. – gdoron Nov 26 '13 at 18:07
4
if (val.indexOf('http://') === -1 && val.indexOf('https://') === -1) {
    val = 'http://' + val;
}

You could also use a regex:

if(!/^https?:\/\//.test(val)) {
    val = 'http://' + val;
}
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636