P Clegg P Clegg - 1 year ago 139
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.

Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download