Split folder path string

If I have a file path, for example:

var/www/parent/folder 

How can I delete the last folder to return:

 var/www/parent 

Folders can have any name, I'm quite happy with the use of regular expressions.

Thanks in advance.

+6
source share
3 answers

Use the following regular expression to match the last part of the directory and replace it with an 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 such a path, you need to use the folloiwng pattern (to match the optional last / ):

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

use the split-> slice-> join function:

 "var/www/parent/folder".split( '/' ).slice( 0, -1 ).join( '/' ); 
+11
source

If this is always the last folder you want to get rid of, the easiest way would be to use substr() and lastIndexOf() :

 var parentFolder = folder.substr(0, folder.lastIndexOf('/')); 

jsfiddle example

+2
source

Source: https://habr.com/ru/post/979715/


All Articles