Java Reference
In-Depth Information
Let's look at the use of the substr() and lastIndexOf() methods together. Later in the topic,
you see how you can retrieve the file path and name of the currently loaded web page. However,
there is no way of retrieving the filename alone. So if, for example, your file is http://mywebsite/
temp/myfile.html , yo u may need to extract the myfile.html part. This is where substr() and
lastIndexOf() are useful:
var fileName = window.location.href;
fileName = fileName.substr(fileName.lastIndexOf("/") + 1);
document.write("The file name of this page is " + fileName);
The first line sets the variable fileName to the current file path and name, such as /mywebsite/
temp/myfile.html . Don't worry about understanding this line right now; you'll see it later.
The second line is where the interesting action is. You can see that this code uses the return value
of the lastIndexOf() method as a parameter for another method, something that's perfectly
correct and very useful. The goal in using fileName.lastIndexOf("/") is to find the position of
the final forward slash ( / ), which will be the last character before the name of the file. You add
one to this value, because you don't want to include that character, and then pass this new value
to the substr() method. There's no second parameter here (the length), because you don't know
it. As a result, substr() will return all the characters right to the end of the string, which is what
you want.
Note This example retrieves the name of the page on the local machine,
because you're not accessing the page from a web server. However, don't
let this mislead you into thinking that accessing files on a local hard drive
from a web page is something you'll be able to do with JavaScript alone.
To protect users from malicious hackers, JavaScript's access to the user's
system, such as access to files, is very limited. You learn more about this
later in the topic.
Converting Case—the toLowerCase() and toUpperCase() Methods
If you want to change the case of a string (for example, to remove case sensitivity when comparing
strings), you need the toLowerCase() and toUpperCase() methods. It's not hard to guess what these
two methods do. Both of them return a string that is the value of the string in the String object,
but with its case converted to either upper or lower depending on the method invoked. Any non‐
alphabetical characters remain unchanged by these functions.
In the following example, you can see that by changing the case of both strings you can compare
them without case sensitivity being an issue:
var myString = "I Don't Care About Case";
 
if (myString.toLowerCase() == "i don't care about case") {
alert("Who cares about case?");
}
 
Search WWH ::




Custom Search