Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

regex - Check if a string starts with http using Javascript

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.

question from:https://stackoverflow.com/questions/11300906/check-if-a-string-starts-with-http-using-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...