简体   繁体   中英

I'd like to remove the filename from a path using JavaScript

Using Javascript I'd like to remove the filename from the end of a string (path+filename), leaving me just the directory path.

Would regular expressions be ideal? Or, is there a simpler means of doing this using the string object?

Thanks for any help!

----ANSWERED & EXPLAINED---

The purpose of this code was to open finder to a directory. The data I was able to extract included a filename - since I was only trying to open finder (mac) to the location, I needed to strip the filename. Here's what I ended up with:

var theLayer = app.project.activeItem.selectedLayers[0];
//get the full path to the selected file
var theSpot = theLayer.source.file.fsName;
//strip filename from the path
var r = /[^\/]*$/;
var dirOnly = theSpot.replace(r, '');
//use 'system' to open via shell in finder
popen = "open"
var runit = system.callSystem(popen+" "+"\""+dirOnly+"\"");
var urlstr = '/this/is/a/folder/aFile.txt';
var r = /[^\/]*$/;
urlstr.replace(r, ''); // '/this/is/a/folder/'

You haven't specified any sample inputs.

Assuming you always have a directory then the following will work. It takes everything up to (but not including) the last slash.

test = "/var/log/apache2/log.txt";
console.log(test.substring(0, test.lastIndexOf("/")));

You can use substring and indexOf:

var url = 'asdf/whatever/jpg.image';
url.substring(0, url.lastIndexOf('/'))

As noted in this answer , if you're using node.js (fair assumption if you're dealing with file paths) - you can use the path module, call path.parse , and retrieve the directory name with dir like this:

const path = require("path")

let myPath = "folder/path/file.txt"
let myDir = path.parse(myPath).dir

console.log(myDir) // "folder/path"

This should be the most robust way to manage and parse file paths across different environments.

I know this is a very old question and has already been answered, however my requirement was to remove the file if it exists in the given path or don't do anything if its folder already.

The accepted answer's regex didn't work for me so I used this one:

let FilePathString = '/this/is/a/folder/aFile.txt';
let FolderPathString = '/this/is/a/folder/';
const RegexPattern = /[^\/](\w+\.\w+$)/i;
console.log(FilePathString.replace(RegexPattern, '')); // '/this/is/a/folder/'
console.log(FolderPathString.replace(RegexPattern, '')); // '/this/is/a/folder/'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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