Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am quite new to Javascript. I wanted to get the filename and extension from a specific folder. For that i am using ActiveXObject and going to the folder using GetFolder and then enumerating through each individual files. The code is given below.

<html>
<script type='text/javascript'>
var myFileNameArray = new Array;
var myFileNameArray = new Array;
function ReadFromFile()
{
    var i;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fsofolder = fso.GetFolder("C:\\Users\\Divya.R");
var colFiles  = fsofolder.Files;
var fc = new Enumerator(colFiles);
for (; !fc.atEnd(); fc.moveNext() )
    { 
        msg += fc.item() + ";";
    }
myFilePathArray = msg.split(";");
for(i=0;i<=myFilePathArray.length;i++)
    {
        myFileNameArray[i] = myFilePathArray[i].split("\\");
    }
document.write(myFileNameArray[0]);
}
</script>
<body onload='ReadFromFile()'>
</body>
</html>

I will get the complete file path in myFilePathArray from each array element i should get the filename. For that I am trying to split again based on '/' and then thought to get the arraylength-1 th element. However the last document write return be a blank page. It doesnt split the myFilePathArray. Please let me know what is wrong with this.

Regards,

Div

share|improve this question

2 Answers 2

Since \ is an escape character it will be ignored. I have found a solution which worked for me. The code is given below.

var msg = "C:\\Users\\Divya.R\\Data.txt;C:\\Users\\Divya.R\\Test2.csv";
var regex = /\\/g;
var fileName="";
var FilePath = msg.replace(regex, "\\\\");
//document.write(FilePath);
var myArray1 = new Array;
var myArray2 = new Array;
myArray1 = FilePath.split(";");
myArray2 =myArray1[0].split("\\");
    for(var i=0;i<=myArray1.length-1;i++)
    {
         myArray2= myArray1[i].split("\\");
         fileName = fileName+myArray2[myArray2.length-1];



    }
//alert(myArray2[myArray2.length-1]);
alert(fileName);

Regards, Divya

share|improve this answer

A simple substr and lastIndexOf would suffice to get your parts:

var path = "C:\\Users\\Divya.R\\Data.txt";
var fileName = path.substr(path.lastIndexOf("\\") + 1);
var ext = path.substr(path.lastIndexOf('.') + 1); // txt
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.