Another few useful JavaScript functions when working with file and directory paths

Whilst working on a project recently, I was having to deal with physical file locations.  In .NET there is the extremely useful object Path, which yields very useful static functions for formatting filenames and directory names etc...  What I did was port a few of the ones which I required to JavaScript.  Hope these of are some help to people.

Hide Code [-]
var Path = {
    ChangeExtension:function(path,extension)
    {
        var regExp = /([a-zA-Z]{1,})$/;
        var matches = regExp.exec(path);
        return path.replace(regExp,extension);
    },
    GetDirectoryName:function(path)
    {
        var regExp = /^[\\]?[:]?([^:\\]*)/;
        var matches = regExp.exec(path);
        return matches[1];
    },
    GetExtension:function(path)
    {
        var regExp = /.([a-zA-Z]{1,})$/;
        var matches = regExp.exec(path);
        return matches[0];
    },
    GetFileName:function(path)
    {
        var regExp = /([^\\]{1,}.[a-zA-Z]{1,})$/;
        var matches = regExp.exec(path);
        return matches[0];
    },
    GetFileNameWithoutExtension:function(path)
    {
        var regExp = /([^.\\]{1,}).[a-zA-Z]{1,}$/;
        var matches = regExp.exec(path);
        return matches[0];
    }
}
{..} Click Show Code

 

Example implementation

Hide Code [-]
var fullpath = 'C:\\Test\\Test.txt';
var filename = Path.GetFileName(fullpath);
{..} Click Show Code

 

Cheers,

 

Andrew :-)

Published Wednesday, April 30, 2008 2:58 PM by REA_ANDREW
Filed under:

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)