Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove last directory in URL

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?

like image 332
pascalhein Avatar asked May 25 '13 14:05

pascalhein


People also ask

How do I find the last segment of a URL?

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.

How do you split a URL?

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.


2 Answers

By using this code remove the last element from the Url link.

url.substring(0, url.lastIndexOf('/')); 
like image 79
Thivan Mydeen Avatar answered Sep 27 '22 17:09

Thivan Mydeen


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/

like image 27
Sharky Avatar answered Sep 27 '22 15:09

Sharky