jQuery / JS:获取当前URL父目录

时间:2013-07-05 21:25:16

标签: javascript jquery url

自:

  

http://www.site.com/example/index.html

我怎样才能得到:

  

http://www.site.com/example/

使用Javascript将其存储到变量中以及如何使用jQuery。提前谢谢。

6 个答案:

答案 0 :(得分:11)

var myURL = "http://www.site.com/example/index.html";
var myDir = myURL.substring( 0, myURL.lastIndexOf( "/" ) + 1);

答案 1 :(得分:3)

http://jsfiddle.net/mXpBx/

var s1 = "http://www.site.com/example/index.html";
var s2 = s1.replace(s1.split("/").pop(),"");

答案 2 :(得分:1)

<强> Fiddle

var a = "http://www.site.com/example/index.html";
var b = a.substring(0, a.lastIndexOf('/'))+"/";

答案 3 :(得分:1)

正则表达式会做同样的事情,但在这个例子中,正则表达式不是最简单的解决方案。

var url = "http://www.site.com/example/index.html";
var newUrl = url.match(/^(.*[\\\/])/)[1];

答案 4 :(得分:1)

$(location).prop("href").split("/").slice(0,-1).join("/")

使用当前页面的演示流程:

  1. $(位置)

    {
        "ancestorOrigins": {
        },
        "hash": "",
        "host": "stackoverflow.com",
        "hostname": "stackoverflow.com",
        "href": "https://stackoverflow.com/questions/17497045/jquery-js-get-current-url-parent-directory",
        "origin": "https://stackoverflow.com",
        "pathname": "/questions/17497045/jquery-js-get-current-url-parent-directory",
        "port": "",
        "protocol": "https:",
        "search": ""
    }
    
  2. $(位置).prop(&#34; HREF&#34)

    https://stackoverflow.com/questions/17497045/jquery-js-get-current-url-parent-directory
    
  3. $(位置).prop(&#34; HREF&#34)。分裂(&#34; /&#34)

    [
        "https:",
        "",
        "stackoverflow.com",
        "questions",
        "17497045",
        "jquery-js-get-current-url-parent-directory"
    ]
    
  4. $(位置).prop(&#34; HREF&#34)。分裂(&#34; /&#34)。片(0,-1)

    [
        "https:",
        "",
        "stackoverflow.com",
        "questions",
        "17497045"
    ]
    

    ※slice()方法选择从给定的start参数开始的元素,并以给定的end参数结束,但不包括。使用负数从数组末尾进行选择。

  5. $(位置).prop(&#34; HREF&#34)。分裂(&#34; /&#34)。片(0,-1)。加入(&#34; /&#34)

    https://stackoverflow.com/questions/17497045
    
  6. 备注和参考:

    • location:位置对象包含有关当前网址的信息。
    • href:当前页面的完整网址。
    • .prop():获取元素的属性值。
    • .split():该方法用于将字符串拆分为子串数组,并返回新数组。
    • .slice():该方法返回数组中的选定元素,作为新的数组对象。
    • .join():该方法将数组的元素连接成一个字符串,并返回该字符串。

答案 5 :(得分:0)

以下似乎有效

new URL(".", "http://example.com/folder/subfolder/file.js")