43

I've been searching all over for an answer to this and all of the answers I've found haven't been in JavaScript.

I need a way, in javascript, to check if a string starts with http, https, or ftp. If it doesn't start with one of those I need to prepend the string with http://. indexOf won't work for me I don't think as I need either http, https or ftp. Also I don't want something like google.com/?q=http://google.com to trigger that as being valid as it doesn't start with an http whereas indexOf would trigger that as being true (if I'm not entirely mistaken).

The closest PHP regex I've found is this:

function addhttp($url) {
   if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
      $url = "http://" . $url;
   }
   return $url;
}

Source: How to add http if its not exists in the url

I just don't know how to convert that to javascript. Any help would be greatly appreciated.

4

6 回答 6

107
export const getValidUrl = (url = "") => {
    let newUrl = window.decodeURIComponent(url);
    newUrl = newUrl.trim().replace(/\s/g, "");

    if(/^(:\/\/)/.test(newUrl)){
        return `http${newUrl}`;
    }
    if(!/^(f|ht)tps?:\/\//i.test(newUrl)){
        return `http://${newUrl}`;
    }

    return newUrl;
};

测试:

expect(getValidUrl('https://www.test.com')).toBe('https://www.test.com');
expect(getValidUrl('http://www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('    http   :    /  /  www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('ftp://www.test.com')).toBe('ftp://www.test.com');
expect(getValidUrl('www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('://www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('http%3A%2F%2Fwww.test.com')).toBe('http://www.test.com');
expect(getValidUrl('www    .  test.com')).toBe('http://www.test.com');
于 2012-07-02T20:51:20.383 回答
39

这应该有效:

var pattern = /^((http|https|ftp):\/\/)/;

if(!pattern.test(url)) {
    url = "http://" + url;
}

jsFiddle

于 2012-07-02T20:50:10.223 回答
19
var url = "http://something.com"
if( url.indexOf("http") == 0 ) {
    alert("yeah!");
} else {
    alert("No no no!");
}
于 2012-07-02T20:50:21.150 回答
3

这应该有效:

var re = /^(http|https|ftp)/
于 2012-07-02T20:49:36.650 回答
3

进一步完善以前的答案,我曾经new RegExp(...)避免混乱的转义,还添加了一个可选的s.

var pattern = new RegExp('^(https?|ftp)://');

if(!pattern.test(url)) {
    url = "http://" + url;
}

var pattern = new RegExp('^(https?|ftp)://');


console.log(pattern.test('http://foo'));
console.log(pattern.test('https://foo'));
console.log(pattern.test('ftp://foo'));
console.log(pattern.test('bar'));

于 2019-07-17T14:06:30.513 回答
3

非正则表达式声明方式:

const hasValidUrlProtocol = (url = '') => 
    ['http://', 'https://', 'ftp://'].some(protocol => url.startsWith(protocol))
于 2020-05-12T08:46:13.363 回答