Check if a string starts with http using Javascript

前端 未结 6 1361
不思量自难忘°
不思量自难忘° 2021-02-11 14:27

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:30
    var url = "http://something.com"
    if( url.indexOf("http") == 0 ) {
        alert("yeah!");
    } else {
        alert("No no no!");
    }
    
    0 讨论(0)
  • 2021-02-11 14:34

    This should work:

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

    This should work:

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

    jsFiddle

    0 讨论(0)
  • 2021-02-11 14:51

    Non-Regex declarative way:

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

    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)
提交回复
热议问题