Check if a string starts with http using Javascript

前端 未结 6 1365
不思量自难忘°
不思量自难忘° 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: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');
    

提交回复
热议问题