简体   繁体   English

拆分文件夹路径字符串

[英]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.提前致谢。

使用 split->slice->join 函数:

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

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 / ):如果要删除此类路径的最后一部分,则需要使用以下模式(匹配可选的 last / ):

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

If it's always the last folder you want to get rid of, the easiest method would be to use substr() and lastIndexOf() :如果它始终是您想要删除的最后一个文件夹,最简单的方法是使用substr()lastIndexOf()

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

jsfiddle example jsfiddle 示例

This is no specialized version of split per se, but you can split by the path.sep like so:这本身并不是split专门版本,但您可以通过path.sep进行拆分,如下所示:

import path from 'path';

filePath.split(path.sep);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM