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?
Explanation. The split() method first splits the url into an array of elements separated by the / then pop () method helps us to get the last element of an array (that is our url last segment). Similarly, we can also get the last segment by using the combination of substring() , lastIndexOf() methods.
To split the URL to get URL path in with JavaScript, we can create a URL instance from the URL string. Then we can use the pathname property to get the URL path. For instance, we write: const url = 'http://www.example.com/foo/path2/path3/path4'; const { pathname } = new URL(url); console.
By using this code remove the last element from the Url link.
url.substring(0, url.lastIndexOf('/'));
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With