jQuery / JS:获取当前URL父目录
从:
http://www.site.com/example/index.html
我怎么才能得到:
http://www.site.com/example/
并使用Javascript将其存储到变量中以及如何使用jQuery。 提前致谢。
var myURL = "http://www.site.com/example/index.html"; var myDir = myURL.substring( 0, myURL.lastIndexOf( "/" ) + 1);
var s1 = "http://www.site.com/example/index.html"; var s2 = s1.replace(s1.split("/").pop(),"");
小提琴
var a = "http://www.site.com/example/index.html"; var b = a.substring(0, a.lastIndexOf('/'))+"/";
正则表达式也会这样做,但在这个例子中,正则表达式不是最简单的解决方案。
var url = "http://www.site.com/example/index.html"; var newUrl = url.match(/^(.*[\\\/])/)[1];
$(location).prop("href").split("/").slice(0,-1).join("/")
使用当前页面进行演示过程:
-
$(位置)
{ "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": "" }
-
$(位置).prop( “HREF”)
https://stackoverflow.com/questions/17497045/jquery-js-get-current-url-parent-directory
-
$(位置).prop( “HREF”)。分裂( “/”)
[ "https:", "", "stackoverflow.com", "questions", "17497045", "jquery-js-get-current-url-parent-directory" ]
-
$(位置).prop(的 “href”)。分裂( “/”)。片(0,-1)
[ "https:", "", "stackoverflow.com", "questions", "17497045" ]
※slice()方法选择从给定的start参数开始的元素,并以给定的end参数结束,但不包括。 使用负数从数组的末尾进行选择。
-
$(位置).prop(的 “href”)。分裂( “/”)。片(0,-1)。加入( “/”)
https://stackoverflow.com/questions/17497045
注释和参考:
- location :location对象包含有关当前URL的信息。
- href :当前页面的整个URL。
- .prop() :获取元素的属性值。
- .split() :该方法用于将字符串拆分为子字符串数组,并返回新数组。
- .slice() :该方法返回数组中的选定元素,作为新的数组对象。
- .join() :该方法将数组的元素连接成一个字符串,并返回该字符串。