Reputation: 401
From:
How can I get just:
And storing it into a variable using Javascript and how using jQuery also. Thanks in advance.
Upvotes: 10
Views: 11982
Reputation: 33
The following seems to work
new URL(".", "http://example.com/folder/subfolder/file.js")
Upvotes: 2
Reputation: 7038
$(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:
Upvotes: 5
Reputation: 176
var s1 = "http://www.site.com/example/index.html";
var s2 = s1.replace(s1.split("/").pop(),"");
Upvotes: 4
Reputation: 550
A regex would do the same, but in this example a regex is not the most simple solution.
var url = "http://www.site.com/example/index.html";
var newUrl = url.match(/^(.*[\\\/])/)[1];
Upvotes: 1
Reputation: 19480
var myURL = "http://www.site.com/example/index.html";
var myDir = myURL.substring( 0, myURL.lastIndexOf( "/" ) + 1);
Upvotes: 12