mike_hornbeck
mike_hornbeck

Reputation: 1622

Replace the filename in Windows '\\' path

I'm trying to remove the filename from a path created in C# (using Server.MapPath, which by default uses \\), like :

C:\\Foo\\Bar\\Baz\\file.js

My current regex looks to be somewhat working in RegExr but in the real application it works just the opposite way :

\/[^\\]+$

What am I missing ?

Upvotes: 1

Views: 7611

Answers (4)

ocodo
ocodo

Reputation: 30248

Since you're doing this in JS just do a String.split operation.

var path = "C:\\Foo\\Bar\\Baz\\file.js";
var separator = "\\";

function getFilenameFromPath(path, separator){
   var segmented = path.split(separator);
   return segmented[segmented.length-1];
}

console.log(getFilename(path, separator));

The RegEx way...

By the way, the only thing wrong with your original RegEx was the leading \ and the missing /

 /[^\\]+$/

Would nails it. (the trailing /g on @JDwyers answer is to make it a global match, that's redundant for your use case.)

So...

path.match(/[^\\]+$/); // == "file.js"

Cheers

Upvotes: 5

Viral Jain
Viral Jain

Reputation: 1014

Since you want the directory path, by removing the file name, thus:

var path = "C:\\Foo\\Bar\\Baz\\file.js";
var separator = "\\"; // make it OS agnostic.
var result="";

function getFilename(path, separator){
   var segmented = path.split(separator);
   for(var i=0; i<segmented.length-1;i++)
   {
        result+=segmented[i]+"\\\\";
   }
   return result;
}
alert(getFilename(path, separator));

Upvotes: 1

JDwyer
JDwyer

Reputation: 844

to keep with your regex:

var s = "C:\\Foo\\Bar\\Baz\\file.js";
var fileName = s.match(/[^​​​​​​\\]+$/​​​​​​​​​​​​g);

Upvotes: 3

Michael Bray
Michael Bray

Reputation: 15265

Why are you using Regular Expressions for this? It is overkill when there is a function provided to do this in the Path class:

string dirName = Path.GetDirectoryName(filename);

There are also similar functions in the Path class to extract the filename, the extension, the path root, etc.

Upvotes: 0

Related Questions