【问题标题】:Rewrite URL Prefix Using Javascript / Jquery使用 Javascript / Jquery 重写 URL 前缀
【发布时间】:2019-11-20 22:16:54
【问题描述】:

我正在使用 javascript 从外部 API 检索一些数据,然后将这些数据显示在 HTML 页面上。

这个返回的数据里面是一个URL,格式如下;

var url = https://img.evbuc.com/moreStuff

我需要重写这个URL,使它以www为前缀,像这样;

var url = https://www.img.evbuc.com/moreStuff

我想使用 javascript 或 jquery 来实现。

我怎样才能做到这一点?对正确代码的解释也很棒。

【问题讨论】:

    标签: javascript jquery url url-rewriting


    【解决方案1】:

    如果您想要适用于任何协议的东西,试试这个正则表达式:

    var url = "https://img.evbuc.com/moreStuff"
    var new_url = url.replace(/^([a-zA-Z][a-zA-Z0-9\.\+\-]*):\/\//, "$1://www.")
    console.log('new URL: ', new_url)
    

    【讨论】:

      【解决方案2】:

      你不需要正则表达式,你可以简单地使用URL api

      let url = "https://img.evbuc.com/moreStuff"
      
      let parsed = new URL(url)
      
      parsed.host = parsed.host.startsWith('www.') ? parsed.host : "www."+ parsed.host
      
      console.log(parsed)

      【讨论】:

      • 是的。但是没有IE support(如果重要的话)
      • @Codekie 我们确实为URL polyfill提供了polyfills@
      • 如果你想使用 polyfills。
      • 如果我担心 IE 支持,我会做的就是担心 IE 支持。
      【解决方案3】:

      您可以使用正则表达式进行搜索和替换。

      以下示例也适用于:

      • http://img.evbuc.com/moreStuff
      • //img.evbuc.com/moreStuff
      • https://img.evbuc.com/moreStuff//someMoreStuff

      function prependUrl(url) {
        return url.replace(/^([^\/]*)(\/\/)(.*)/, '$1//www.$3');
      }
      
      const urls = [
          'https://img.evbuc.com/moreStuff',
          'http://img.evbuc.com/moreStuff',
          '//img.evbuc.com/moreStuff',
          'https://img.evbuc.com/moreStuff//someMoreStuff'
      ];
      
      urls.forEach((url) => console.log(`${ url } -> ${ prependUrl(url) }`));
      • 正则表达式包含 3 个捕获组:

        1. 选择直到第一个/(不包括)的所有内容
        2. 选择//(用于协议根)
        3. 选择其余的
      • 替换值取第一个 / 之前的所有内容(也可能是空字符串)

      • // 替换为//www.
      • 附加其余部分

      【讨论】:

        【解决方案4】:

        简单的字符串操作:

        var url = 'https://img.evbuc.com/moreStuff'
        var newUrl = url.split('//')[0] + '//www.' + url.split('//')[1]
        console.log(newUrl)

        还有另一种方法是这样的:

        var url = 'https://img.evbuc.com/moreStuff'
        var newUrl = url.replace('https://', 'https://www.')
        console.log(newUrl)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-01-13
          • 2020-05-26
          • 2022-11-24
          • 2013-08-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-13
          • 1970-01-01
          相关资源
          最近更新 更多