jQuery/JS: Get current URL parent directory
http://jsfiddle.net/mXpBx/
var s1 = "http://www.site.com/example/index.html";
var s2 = s1.replace(s1.split("/").pop(),"");
Fiddle
var a = "http://www.site.com/example/index.html";
var b = a.substring(0, a.lastIndexOf('/'))+"/";
$(location).prop("href").split("/").slice(0,-1).join("/")
Demo process with the current page:
$(location)
{ "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": "" }
$(location).prop("href")
https://stackoverflow.com/questions/17497045/jquery-js-get-current-url-parent-directory
$(location).prop("href").split("/")
[ "https:", "", "stackoverflow.com", "questions", "17497045", "jquery-js-get-current-url-parent-directory" ]
$(location).prop("href").split("/").slice(0,-1)
[ "https:", "", "stackoverflow.com", "questions", "17497045" ]
※ The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument. Use negative numbers to select from the end of an array.
$(location).prop("href").split("/").slice(0,-1).join("/")
https://stackoverflow.com/questions/17497045
Notes and References:
- location: The location object contains information about the current URL.
- href: The entire URL of the current page.
- .prop(): Get the value of a property for the element.
- .split(): The method is used to split a string into an array of substrings, and returns the new array.
- .slice(): The method returns the selected elements in an array, as a new array object.
- .join(): The method joins the elements of an array into a string, and returns the string.
var myURL = "http://www.site.com/example/index.html";
var myDir = myURL.substring( 0, myURL.lastIndexOf( "/" ) + 1);