Comp 416 – Web Programming

University of North Carolina at Chapel Hill

Javascript Strings and Functions

Due: Wed 10/10

Possible points: 3

For each of the following, you should write Javascript functions that work on any input string, but you are not required to test the functions beyond what is presented in the skeleton.

Primitive String Processing

In the following problems, Use only the primitive string methods (and properties): concatenation (+) == indexing (str[index]), length, charAt() (indexing is usually easier than using charAt). Do not use: match replace indexOf, etc. Use console.log() for all output.

  1. Reversing a String.
    • reverseA. Print the string in reverse. Do not change str itself. For example: str = 'cat' prints out as 'tac' (but on 3 separate lines in the console window)
    • reverseB.Return a new string that is str in reverse order. Do not change str itself
    • reverseC. Modify the parameter, str so that the characters are in reverse order. Examine the versions of this. It can't be done. Strings are passed by value not by reference.
    • reverseStringsAsArrayElements - given an array of strings, modify the array so that each element is reversed. Now, this is possible since arrays are passed by reference.
  2. Counting characters in a String.
    • countX - return a count of the number of times the letter 'X' appears in the string.
    • countVowels - return a count of the number of times a vowel appears in the string. Count 'aeiou' as vowels but not 'y'.
    • count(str,fn) - Note how the execution structure of countX and countVowels is exactly the same. The only difference is the criteria used for counting. This is the Template Design Pattern. Javascript (unlike Java or C++) treats functions just as other objects. A function, fn, can be passed as a parameter. Write a general counting function, count(str,fn), where fn is a function that takes one parameter which must be a single character. The function returns either true or false. True means count it and false means dont count it. In Java terms: boolean fn(char c) . Write an isVowel(ch) method. You will get the same value returned from countVowels(str) as from count(str,isVowel).

All output will be in the Firebug console. Your output should be like this screen shot.

Requirements

The script in the head element of this page contains the skeleton for this program. It starts with a 'main' section that calls each of the methods you are to write. You do not have to change the 'main' section. Fill in the code for each of the methods. You do not have to test or include a Test Plan.

Turn in the following in the following order:

  1. Cover sheet
  2. Your Javascript code. Do not turn in your HTML code.
  3. Screen shot of your output.

The following assignment will be 'Advanced String Processing' using: match, replace, indexOf.

Learning Objectives

Javascript string, method writing, methods as objects, and parameter passing