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 is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
user1339164
  • 347
  • 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 is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
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
  • 298,938
  • 77
  • 579
  • 623