【问题标题】:Add "/path/" in the middle of an URL in JavaScript在 JavaScript 中的 URL 中间添加“/path/”
【发布时间】:2018-06-24 20:13:09
【问题描述】:

如何在 JavaScript 中有效地将“路径”添加到 URL 的中间?

我想将 embed 添加到 URL,所以 URL https://blog.com/post/123 最终会看起来像这样 https://blog.com/embed/post/123

干杯

【问题讨论】:

标签: javascript string url split


【解决方案1】:

您可以创建<a> 并设置href 属性。然后在路径名前加上embed 并使用toString() 获取整个URL。

let element = document.createElement('a');
element.href = 'https://blog.com/post/123';
element.pathname = 'embed' + element.pathname;
console.log(element.toString());

【讨论】:

【解决方案2】:

如果路径只是一个字符串,你可以这样做

var path = "https://blog.com/post/123";
var withEmbed = path.replace(/\/post\//,'/embed/post/');
console.log(withEmbed);

【讨论】:

    【解决方案3】:

    您可以使用位置 API。

    https://developer.mozilla.org/en-US/docs/Web/API/Location

    function addEmbed(location) {
        return location.protocol + '//' + location.host +
            '/embed' + location.pathname;
    }
    
    var url = document.createElement('a');
    url.href = 'https://blog.com/post/123';
    
    var embed = addEmbed(url);
    console.log(embed);  // "https://blog.com/embed/post/123"
    

    示例:https://codepen.io/anon/pen/wXxvaq

    【讨论】:

      【解决方案4】:

      我这样做的方式是通过 ref/value 将原始 URL 和您要添加的文本传递到一个函数中。然后它会删除“https://”(如有必要),在第一个“/”处拆分 url 并将每个部分保存为 var。最后,它将所有内容重新组合在一起并将其输出到

      在 html 页面上。 这不必以这种方式输出,它可以保存为全局变量,然后在链接中使用(但我不知道你的计划是什么所以我输出了它):)

      function addToURL(URL, add) {
          URL = URL.replace(/(^\w+:|^)\/\//, '');
          var part1 = URL.substring(0, URL.indexOf("/") + 1);
          var part2 = URL.substring(URL.indexOf("/"), URL.length);
          var result = "https://" + part1 + add + part2;
          document.getElementById("demo").innerHTML = result;
      }
      

      这是我做的例子:https://codepen.io/anon/pen/RJBwZp

      希望这会有所帮助:P

      【讨论】:

        猜你喜欢
        • 2019-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-20
        • 2018-12-24
        • 1970-01-01
        相关资源
        最近更新 更多