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+"\"");
The method fileCompinent() is used to remove the path information from a filename and return only its file component. This method requires a single parameter i.e. the file name and it returns the file component only of the file name.
How to remove extension from filename JavaScript? function removeExtension(filename) { return filename. substring(0, filename.To remove a file extension from a string in Node.
The replace() method is one of the most commonly used techniques to remove the character from a string in javascript. The replace() method takes two parameters, the first of which is the character to be replaced and the second of which is the character to replace it with.
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/'
var urlstr = '/this/is/a/folder/aFile.txt';
var r = /[^\/]*$/;
urlstr.replace(r, ''); // '/this/is/a/folder/'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With