| Click on the button that follows and see what, if anything
happens!
As files, grow up, one of the first things they learn is to say their name. So this one
is old enough!
Here is the code for the function that gets the file's name. Remember that we want the
name of the file, in this case, and not the whole URL.
<script type= "text/javascript">
<!-- //
function FileName()
{
if (location.href.lastIndexOf('/') !=-1)
// Check whether '/' exists.
{
// If it does then we ...
firstpos=location.href.lastIndexOf( '/')+1;
/* The URL is
'http://www.trans4mind.com/personal_development/JavaScript2/lastIndexOf.htm' . We use
lastIndexOf and we find the last example of '/' - the first position for counting is here.
*/
// Find the first position (the file starts after this)
lastpos=location.href.length;
/* Normally, the last position of the filename will be at the end of the
complete URL - although it could have a # and a name at the end!*/
Namer=location.href.substring(firstpos,lastpos);
// We extract the string (the file's name).
alert( 'My name is "'+Namer+'"');
// And reveal all to the clicker!
}
}
//-->
</script>
The filenames at the bottom of this page giving the next
and previous lessons are actually written by JavaScript (As I couldn't be bothered!) So
finding the name of a file is important.
We could do much the same thing using charAt(), but we
would have to write a lot more code to achieve the same results. I suppose your mind is
racing ahead and thinking of all the uses of these string functions - database search, and
all sorts of finding tasks!
|