javascript 文件夹路径的分割字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27509722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:34:30  来源:igfitidea点击:

Split string of folder path

javascriptregexstring

提问by P Clegg

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.

提前致谢。

回答by TheGr8_Nik

use the split->slice->join function:

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

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

回答by falsetru

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"

回答by newfurniturey

If it's always the lastfolder 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 示例