Check if a string starts with http using Javascript

前端 未结 6 1849
闹比i
闹比i 2021-02-11 13:56

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 sta

相关标签:
6条回答
  • 2021-02-11 14:33

    This should work:

    var re = /^(http|https|ftp)/
    
    0 讨论(0)
  • 2021-02-11 14:34
    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;
    };
    

    Tests:

    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');
    
    0 讨论(0)
  • 2021-02-11 14:36

    Non-Regex declarative way:

    export const hasValidUrlProtocol = (url = '') => 
        Boolean(['http://', 'https://', 'ftp://'].some(protocol => url.startsWith(protocol)))
    
    0 讨论(0)
  • 2021-02-11 14:37

    This should work:

    var pattern = /^((http|https|ftp):\/\/)/;
    
    if(!pattern.test(url)) {
        url = "http://" + url;
    }
    

    jsFiddle

    0 讨论(0)
  • 2021-02-11 14:51
    var url = "http://something.com"
    if( url.indexOf("http") == 0 ) {
        alert("yeah!");
    } else {
        alert("No no no!");
    }
    
    0 讨论(0)
  • 2021-02-11 14:53

    Refining previous answers a bit more, I used new RegExp(...) to avoid messy escapes, and also added an optional 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'));

    0 讨论(0)
提交回复
热议问题