More Exercises with JavaScript Functions
CSCI 2910-001 In-Class Exercise

You should be able to...

This exercise has a number of purposes. They include:

String functions

In last week's lecture, we discussed a number of JavaScript string functions that allowed us to examine and manipulate strings. They included:

The first exercise today will be to use these functions to create four special functions of our own. Open up your XHTML template and save a copy in your inclass/html directory under the name "str_func.htm". In it, add the script tags for JavaScript in the head. Between these tags, create the following four functions:

reverseChars(str_arg):

This first function, reverseChars(str_arg), will return a string containing the characters of the string str_arg in reverse order. For example, if reverseChars("tarnoff") is called, the return value will be "ffonrat". Basically, you will create a new string (the one that is returned) character by character by retrieving the characters backwards from str_arg.

To test the code, you might want to use some HTML like the following in the body of your document:

<h2>Testing reverseChars() Function</h2>

<script language="javascript" type="text/javascript">
<!--
    document.writeln("<p>The output of reverseChars(&quot;tarnoff&quot;) is: " + reverseChars("tarnoff") + "</p>");
// -->
</script>

<h2>End of reverseChars() Function Test</h2>

The output of the above code should be:

The output of reverseChars("tarnoff") is: ffonrat

reverseWords(str_arg):

The second function, reverseWords(str_arg), will return a string containing the words of the string str_arg in reverse order. For example, if reverseChars("The quick brown fox jumps over the lazy dog") is called, the return value will be "dog lazy the over jumps fox brown quick The". This function has three steps. First, break the string into an array of words using split(' '). Next, reverse the order of the words by creating a new array and populating it with words from the first array. (This should be similar to what you did for the previous exercise.) Third, use the array function join() to create a return string from the reversed array.

To test the code, you might want to use some HTML like the following in the body of your document:

<h2>Testing reverseWords() Function</h2>

<script language="javascript" type="text/javascript">
<!--
    document.writeln("<p>The output of reverseWords(&quot;The quick brown fox jumps over the lazy dog&quot;) is: " + reverseWords("The quick brown fox jumps over the lazy dog") + "</p>");
// -->
</script>

<h2>End of reverseWords() Function Test</h2>

The output of the above code should be:

The output of reverseWords("The quick brown fox jumps over the lazy dog") is: dog lazy the over jumps fox brown quick The

toSentenceCase(str_arg):

This third function will be used to force a sentence to have the first word capitalized and the rest in lower case. Basically, you want to capitalize the first character of str_arg and force the rest to lower case. Try concatenating the following two strings:

The concatenated string should be in sentence case and good to be returned. Use the following code to test your function.

<h2>Testing toSentenceCase() Function</h2>

<script language="javascript" type="text/javascript">
<!--
    document.writeln("<p>The output of toSentenceCase(&quot;i LOVE ClienT SidE ProgramminG!&quot;) is: " + toSentenceCase("i LOVE ClienT SidE ProgramminG!") + "</p>");
// -->
</script>

<h2>End of toSentenceCase() Function Test</h2>

The output of the above code should be:

The output of toSentenceCase("i LOVE ClienT SidE ProgramminG!") is: I love client side programming!

toTitleCase(str_arg):

The last function will be used to force a sentence to have every word capitalized and the rest in lower case, i.e., title case. (Don't worry about the fact that we aren't supposed to capitalize words like "the", "of", "and" unless they are the first word of the title.) I would suggest that you could write this function by breaking the sentence into an Array of words, calling toSentenceCase() for each of the words, then putting the sentence back together. This is the way I did it:

You can use the following code to test your function.

<h2>Testing toTitleCase() Function</h2>

<script language="javascript" type="text/javascript">
<!--
    document.writeln("<p>The output of toTitleCase(&quot;i LOVE ClienT SidE ProgramminG!&quot;) is: " + toTitleCase("i LOVE ClienT SidE ProgramminG!") + "</p>");
// -->
</script>

<h2>End of toTitleCase() Function Test</h2>

The output of the above code should be:

The output of toTitleCase("i LOVE ClienT SidE ProgramminG!") is: I Love Client Side Programming!

Using the Date Object

First, let's get comfortable with initializing a Date object. There are two ways that I want you to be able to initialize a date: initializing it to the current date and time and initializing it to a specific date in the future. Remember that to create an instance, we need to use the new keyword. To create an instance of the Date object initialized to the current time, we use the following code:

now = new Date();

To test this, open your template again and save it in your inclass/html folder as the file "date.html". Insert the appropriate JavaScript tags within the body, and between the tags insert the code:

now = new Date();
document.write("<p>The current date and time is: " + now + "</p>");

We also need to be able to initialize a date and time other than the current date and time. To do that, we need to be able to access the functions of the Date object that set its properties. These include setMonth(), setDate(), setYear(), setHours(), setMinutes(), and setSeconds(). Notice that you do not set these properties directly, you use the function calls. To try to set the properties directly may cause an error. Now add the following code to the script you added to your HTML body:

freedom = new Date();
freedom.setMonth(4); // Remember 0 = January
freedom.setDate(3);
freedom.setYear(2007);
freedom.setHours(10);
freedom.setMinutes(0);
freedom.setSeconds(0);
document.write("<p>I will be through with CSCI 2910 on: " + freedom + "</p>");

Now let's create a countdown clock of sorts. What we will do is take the target date (the end of the CSCI 2910 final exam time), and subtract from it the current time. This will give us the number of milliseconds between now and then. Let's start by moving the declarations for now and freedom to a function called countdown().

function countdown()
{
// Create Date object containing current time
    now = new Date();

// Create Date object containing time of end of CSCI 2910 exam
    freedom = new Date();
    freedom.setMonth(4)
    freedom.setDate(3);
    freedom.setYear(2007);
    freedom.setHours(10);
    freedom.setMinutes(0);
    freedom.setSeconds(0);
}

Now, we will use the getTime() function to retrieve the milliseconds since January 1, 1970 for both now and freedom. Subtracting now from freedom will give us the number of milliseconds until we get out of here. Dividing by 1000 will convert that value to seconds. Add the following code to your function right below the declaration of freedom.

// Using getTime() to retrieve milliseconds since 1/1/70 for both freedom
// and now, we can find the difference in milliseconds. Dividing by 1000
// turns the difference into seconds.

    time_til_freedom = Math.round((freedom.getTime() - now.getTime()) / 1000);

Just in case we use this function AFTER we get out of this class, set any negative values to zero. Do this by adding the following code after the initialization of time_til_freedom.

// Eliminate negative values

    if(time_til_freedom < 0) time_till_freedom = 0;

Now, we need to calculate the number of days, hours, minutes, and seconds until we get out of here. If we perform an integer divide on time_til_freedom by 24 hours/day times 60 minutes/hour times 60 seconds/minute, we should get an integer result that represents the number of days left. The remainder of this division will be the partial day left over in seconds. Divide the partial day by 60 minutes/hour times 60 seconds/minute and we should get the integer number of hours into the partial day along with a remainder representing the number of seconds into the next hour. Divide the remainder by 60 and we should get the number of minutes with a remainder representing the number of seconds. This is all taken care of with the code shown below. Insert it after your "negative check".

    var days_left = Math.floor(time_til_freedom/(24*60*60));
    time_til_freedom %= (24*60*60);
    var hours_left = Math.floor(time_til_freedom/(60*60));
    time_til_freedom %= (60*60);
    var minutes_left = Math.floor(time_til_freedom/60);
    var seconds_left = time_til_freedom %= 60;

Last of all, we need to output the value to the user. For now, let's do this in an alert box. Begin by creating an empty string. Follow this by initializing the string with a string displaying the number of days, hours, minutes, and seconds left until 3:20 PM on May 4, 2006. This string can then be output to an alert box. The following code does this.

var output_string = new String();
output_string = days_left + " days " + hours_left + " hours " + minutes_left + " minutes " + seconds_left + " seconds ";
window.alert(output_string);

All of this code is well and good except for the fact that there is no way to call it. Let's create a button on our web page that when clicked calls the countdown() function. I would simply add a form in the body of the HTML document with a button that called countdown() for an onClick event.

<form name="output" id="output">
    <input type="button" onClick="countdown();" value="Time 'til we're done with 2910">
</form>

Load your page and see if the code works!

Timers

JavaScript provides a way for a programmer to load a millisecond timer with an integer such that when that timer counts down to zero, a function can be called. The JavaScript function that does this is called setTimeout().

[intervalID =] window.setTimeout(expression or function_name, milliseconds_til_timeout) -- initializes a timer that will call a specified function (function_name) or evaluate an expression after the specified number of milliseconds has elapsed. The function returns a value that can be used to identify the timer so that it may be cleared before the time has expired.

Let's use this feature to force our countdown() function to be called every second in order to update a displayed time.

Load your page and click the button! Does it work?