get the filename of a path using String.lastIndexOf()

M

Matt

In test() method:
var path="C:\test\hello.txt"; //returns -1 for path.lastIndexOf("\\").
why??
var pos=path.lastIndexOf("\\"); //return -1

But in showFile() method:
We are able to get the filename. The only difference is test()
hardcode the path,
but in showFile() we gets the path from the file dialog.

Please advise. thanks!!

<script type="text/javascript">
function test()
{ //var path="C:\\test\\hello.txt"; //good, it works
var path="C:\test\hello.txt"; //returns -1 for
path.lastIndexOf("\\"). why??
var pos=path.lastIndexOf("\\"); //unterminate string constant, use
"\\" for backslash
alert("pos=" + pos);
var filename = path.substring(pos+1);
alert(filename);
}

function showFile()
{ var path= InputForm.f1.value;
alert("path=" + path);
var pos=path.lastIndexOf("\\"); //unterminate string constant, use
"\\" for backslash
alert("pos=" + pos);
var filename = path.substring(pos+1);
InputForm.filename.value = filename;
}
</script>
<form name="InputForm" action="page2.asp" method="post">
<P><input type="button" name="b1" value="test file button"
onClick="test()">
<P>File Name: <input type="text" name="filename">
<P><input type="FILE" name="f1" onChange="showFile()">
</form>
 
M

Michael Winter

In test() method:
var path="C:\test\hello.txt";
//returns -1 for path.lastIndexOf("\\").
why??

The backslash within a literal is an escaping character. The string, path,
above actually produces:

"C:<TAB>esthello.txt"

which you should see with

alert(path);
var pos=path.lastIndexOf("\\"); //return -1

That's why you need to (and do, correctly) escape the backslash in the
lastIndexOf call, as well.
But in showFile() method:
We are able to get the filename. The only difference is test()
hardcode the path,
but in showFile() we gets the path from the file dialog.

As I already said, with literals, defined with quotes, the backslash acts
as an escaping character. With a value - an evaluated literal, or obtained
from a property - the backslash is just a backslash; it has no meaning.
That's the difference between values and literals.

Hope that makes sense,
Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top