user1339164
user1339164

Reputation: 357

search for http:// and https:// in a string

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://.

Upvotes: 1

Views: 4061

Answers (2)

gdoron
gdoron

Reputation: 150253

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

The regex way is:

if (!val.search(/^http[s]?:\/\//)){
    val = 'http://' + val;        
}

Upvotes: 8

ThiefMaster
ThiefMaster

Reputation: 318508

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;
}

Upvotes: 4

Related Questions