Get relative URL from absolute URL

后端 未结 8 1961
自闭症患者
自闭症患者 2020-12-03 04:42

I want to get the relative URL from an absolute URL in JavaScript using regex and the replace method.

I tried the following but it is not working:

va         


        
8条回答
  •  没有蜡笔的小新
    2020-12-03 05:13

    URL.getRelativeURL

    There's an public-domain extension for the standard URL object called getRelativeURL.
    It's got a few cool tweaks like force reload, you should check it out!

    Try it live.       View on Gist.


    Example usage

    //syntax: .getRelativeURL()
    
    //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";
    

提交回复
热议问题