【问题标题】:Get relative URL from absolute URL从绝对 URL 获取相对 URL
【发布时间】:2011-09-09 22:40:23
【问题描述】:

我想使用 regex 和 replace 方法从 JavaScript 中的绝对 URL 获取相对 URL。

我尝试了以下方法,但它不起作用:

var str="http://localhost/mypage.jsp";
document.write(str.replace("^[\w]*\/\/[\w]*$",""));

【问题讨论】:

  • 我希望输出为/mypage.jsp 以提供http://localhost/mypage.jsp

标签: javascript regex url


【解决方案1】:

一个很好的方法是使用浏览器的本机链接解析功能,使用a 元素:

function getUrlParts(url) {
    var a = document.createElement('a');
    a.href = url;

    return {
        href: a.href,
        host: a.host,
        hostname: a.hostname,
        port: a.port,
        pathname: a.pathname,
        protocol: a.protocol,
        hash: a.hash,
        search: a.search
    };
}

然后您可以使用getUrlParts(yourUrl).pathname 访问路径名。

属性与location 对象的属性相同。

【讨论】:

  • 路径名不会返回query (a.search) 和hash。对我来说,更好的变体是var urlParts = getUrlParts(yourUrl); var absoluteUrl = urlParts.pathname + urlParts.search + urlParts.hash
【解决方案2】:

如果“相对 URL”是指第一个 / 之后的字符串部分,那么很简单:

document.write(str.replace(/^(?:\/\/|[^/]+)*\//, ''));

这匹配字符串中第一个/ 之前的所有字符,并将它们替换为空字符串。

输入:http://localhost/my/page.jsp --> 输出:/my/page.jsp

【讨论】:

  • @Tim - 它不像你说的那样工作。让我知道整个网址:(
  • 嗯,奇怪。试试str.replace(/^(?:\/\/|[^\/]+)*\//, "");,现在怎么样?
  • @Tim - 是的,现在可以了。但还有一点问题。我想要第二张单曲/ 之后的部分,你能帮我修改这个正则表达式吗?
  • @Tim - 嘿,谢谢 Tim +1,我使用str.replace(/[\w]*:\/\/[\w]*\/[\w]*/,"") 让它工作了,但仍在等待您采用的解决方案。 :)
  • 在您的示例中(在您的问题中)只有一个斜杠 - 那么应该发生什么?
【解决方案3】:

sn -p 下面返回页面的绝对URL。

 var myURL = window.location.protocol + "//" + window.location.host  + window.location.pathname;

如果你只需要相对 url 就使用下面的 sn-p

 var myURL=window.location.pathname;

查看get relative URL using Javascript 了解更多详细信息以及实现相同功能的多种方法。

【讨论】:

  • location.pathname 是获得相对形式的活动 url 的明显赢家!但是为什么不直接使用location.href 作为绝对网址呢?
  • window.location.pathname 显然是这里的正确答案时,这是怎么回事???
  • 这个答案不正确;如果 URL 有查询或散列,它们将在不应该的时候被省略。
【解决方案4】:

const url = new URL('https://www.example.com/path/#anchor?query=value');
const rel = url.toString().substring(url.origin.length)

console.log(rel)
// Output: /path/#anchor?query=value

 

【讨论】:

  • 这对我来说非常有效,看起来是最简单的答案。
【解决方案5】:

不要使用正则表达式等低级的东西。这些问题已经被很多其他人解决了。尤其是边缘情况。

看看URI.js,它应该可以完成这项工作:http://medialize.github.io/URI.js/docs.html#relativeto

var uri = new URI("/relative/path");
// make path relative
var relUri = uri.relativeTo("/relative/sub/foo/sub/file"); // returns a new URI instance
// relUri == "../../../path"

【讨论】:

    【解决方案6】:

    URL.getRelativeURL

    标准URL 对象有一个公共域扩展名为getRelativeURL
    它有一些很酷的调整,例如 强制重新加载,您应该检查一下!

    Try it live.     View on Gist.


    示例用法

    //syntax: <URL to convert>.getRelativeURL(<relative to this URL>)
    
    //link from Mypage to Google
    a = new URL("https://google.com/search");
    a.getRelativeURL("https://mypage.com")
    == "//google.com/search";
    
    //link from the current location.href
    a.getRelativeURL();
    
    //link from Olutsee to Polk
    var from = new URL("http://usa.com/florida/baker/olutsee");
    var to   = new URL("http://usa.com/florida/polk");
    to.getRelativeURL(from) == "../../polk";
    

    【讨论】:

    • 请注意,您必须在 Gist 中包含代码,并且它会修改 URL.prototype
    【解决方案7】:

    不要忘记\ 是字符串中的转义字符,因此如果您想在字符串中编写正则表达式,请确保为每个需要的\ 键入两次\。示例:/\w/"\\w"

    【讨论】:

      【解决方案8】:

      您可以在下面找到脚本,这里我们只有一个问题,即一项手动工作,我们要添加拆分属性,即,如果您的站点链接是:Get relative URL from absolute URL

      我们想要的网址如下: /questions/6263454/get-relative-url-from-absolute-url

      所以在下面的代码中我们必须添加 .com 而不是 .net 即, var res = at.split(".net");在这里,我们要根据我们的要求添加,现在我需要在 .com 之后分隔,因此代码将是“var res = at.split(".com");”。

      如果您仍有疑问,请告诉我,我认为你们明白这一点 并通过检查来查看代码的变化:

      $(document).ready(function(){
      	$("a").each(function(){
          var at= $(this).attr("href");
          var res = at.split(".net");
          var res1 = res[0];
          var res2 = res[1];
          alert(res2);
          $(this).attr("href",res2);
        });
      });
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <div id="banner-message">
        <p>Hello World</p>
        <a href="https://jsfiddle.net/boilerplate/jquery2">Change color</a>
      </div>
      <div id="banner-message">
        <p>Hello World</p>
        <a href="https://jsfiddle.net/boilerplate/jquery3">Change color</a>
      </div>

      【讨论】:

        猜你喜欢
        • 2010-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-14
        • 2012-08-27
        • 1970-01-01
        相关资源
        最近更新 更多