简体   繁体   中英

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

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

The regex way is:

if (!val.search(/^http[s]?:\/\//)){
    val = 'http://' + val;        
}
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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM