I am trying to remove the last directory part of an URL. My URL looks like this:
https://my_ip_address:port/site.php?path=/path/to/my/folder
.
When clicking on a button, I want to change this to
https://my_ip_address:port/site.php?path=/path/to/my
. (Remove the last part).
I already tried window.location.replace(//[A-Za-z0-9%]+$/, "")
, which results in
https://my_ip_address:port/undefined
.
What Regex should I use to do this?
Advertisement
Answer
Explanation: Explode by “/”, remove the last element with pop, join again with “/”.
function RemoveLastDirectoryPartOf(the_url) { var the_arr = the_url.split('/'); the_arr.pop(); return( the_arr.join('/') ); }
see fiddle http://jsfiddle.net/GWr7U/