【问题标题】:Check if a string starts with http using Javascript使用Javascript检查字符串是否以http开头
【发布时间】:2012-07-03 07:03:48
【问题描述】:

我一直在寻找这个问题的答案,但我找到的所有答案都没有在 JavaScript 中。

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

我发现的最接近的 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

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

【问题讨论】:

标签: javascript regex


【解决方案1】:

这应该可行:

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

【讨论】:

    【解决方案2】:

    这应该可行:

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

    jsFiddle

    【讨论】:

      【解决方案3】:
      var url = "http://something.com"
      if( url.indexOf("http") == 0 ) {
          alert("yeah!");
      } else {
          alert("No no no!");
      }
      

      【讨论】:

      • 如果你有SPACE http,则修剪网址,而不是它有问题:P
      • 如果网址是这样的:“javascript://somethinghttp.com”
      • 在这种情况下并不重要,因为问题是“如何知道字符串是否以 http 开头”
      【解决方案4】:
      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;
      };
      

      测试:

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

      【讨论】:

      • 我建议添加对“url”值的检查,以避免在没有提供值(或空)字符串时返回“http://”:if (url && !/^(f| ht)tps?:\/\//i.test(url))
      • 我总是得到“未定义”的回复。你能提供一个codepen或jsfiddle吗?
      【解决方案5】:

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

      【讨论】:

        【解决方案6】:

        非正则表达式声明方式:

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

        【讨论】:

        • 这是一个很好的答案! +1 声明性!但是你需要Boolean吗? .some() 不是已经返回布尔值了吗?
        猜你喜欢
        • 1970-01-01
        • 2012-02-06
        • 2023-01-01
        • 2011-05-04
        • 2018-12-27
        • 1970-01-01
        • 1970-01-01
        • 2019-08-24
        相关资源
        最近更新 更多