Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
23
rated 0 times [  30] [ 7]  / answers: 1 / hits: 20430  / 10 Years ago, tue, december 16, 2014, 12:00:00

If I have a file path such as:



var/www/parent/folder


How would I go about removing the last folder to return:



var/www/parent


The folders could have any names, I'm quite happy using regex.



Thanks in advance.


More From » regex

 Answers
3

Use the following regular expression to match the last directory part, and replace it with empty string.



//[^/]+$/





'var/www/parent/folder'.replace(//[^/]+$/, '')
// => var/www/parent


UPDATE



If the path ends with /, the above expression will not match the path. If you want to remove the last part of the such path, you need to use folloiwng pattern (to match optional last /):



'var/www/parent/folder/'.replace(//[^/]+/?$/, '')
// => var/www/parent

[#68469] Saturday, December 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kourtney

Total Points: 368
Total Questions: 103
Total Answers: 85

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
kourtney questions
Sun, Oct 4, 20, 00:00, 4 Years ago
Tue, Oct 29, 19, 00:00, 5 Years ago
Thu, Apr 4, 19, 00:00, 5 Years ago
Fri, Mar 1, 19, 00:00, 5 Years ago
;