P Clegg P Clegg - 4 months ago 37
Javascript Question

Split string of folder path

If I have a file path such as:


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


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

Thanks in advance.


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"


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"