P Clegg P Clegg - 8 days ago 8
Javascript Question

Split string of folder path

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.

Answer

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"