Javascript 使用Javascript检查字符串是否以http开头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11300906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:22:29  来源:igfitidea点击:

Check if a string starts with http using Javascript

javascriptregex

提问by Peter

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

我一直在寻找这个问题的答案,而我找到的所有答案都没有出现在 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.comto 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).

我需要一种在 javascript 中检查字符串是否以 http、https 或 ftp 开头的方法。如果它不是以其中之一开头,我需要在字符串前加上http://. indexOf 对我不起作用我认为不需要,因为我需要 http、https 或 ftp。此外,我不希望google.com/?q=http://google.com触发它是有效的,因为它不是以 http 开头,而 indexOf 会触发它为真(如果我没有完全弄错的话)。

The closest PHP regex I've found is this:

我发现的最接近的 PHP 正则表达式是这样的:

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

来源:如果 http 不存在于 url 中,如何添加 http

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

我只是不知道如何将其转换为 javascript。任何帮助将不胜感激。

回答by user123444555621

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');

回答by tskuzzy

This should work:

这应该有效:

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

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

jsFiddle

js小提琴

回答by nicowernli

var url = "http://something.com"
if( url.indexOf("http") == 0 ) {
    alert("yeah!");
} else {
    alert("No no no!");
}

回答by elclanrs

This should work:

这应该有效:

var re = /^(http|https|ftp)/

回答by Steven Spungin

Refining previous answers a bit more, I used new RegExp(...)to avoid messy escapes, and also added an optional s.

进一步完善以前的答案,我曾经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'));

回答by Shota

With new ES6 Features:

具有新的 ES6 特性:

export const hasValidUrlProtocol = (url) => 
    Boolean(['http://', 'https://', 'ftp://'].some(protocol => url.startsWith(protocol)))