Assignment 3 (pdf)

Make sure to test all your answers in the console.

  1. For this question, we assume we have defined a string var s = "cars , trucks,bikes". So there are words, and they are separated by commas, but there might be one or more spaces (or possibly even tabs) on either side of those commas. You should not make any assumptions about how many spaces there are. You can assume that there are no spaces at the very beginning or at the very end.
    1. What regular expression r should we use, so that s.split(r) returns the array ["cars", "trucks", "bikes"]? Make sure that your regular expression removes those spaces too, the resulting array should contain only the words without any spaces.
    2. Now need a regular expression, so that s.match(/../g) would result in the same array. Notice that we are using a “g” so that the regular expression matches as many times as it can. So the regular expression that you provide should be the one that matches just a single word.
    3. Suppose I want to use s.substr(i, j) in this specific example in order to get back the string "trucks". What would i, j be?
    4. Same as the previous question, but now for a call s.substring(i, j).
  2. Write a function average that takes as an argument an array arr. It should return the average of the values in the array: So it adds all the values up, then divides by the array length. Do not forget the return statement and to test your function.
  3. Write a function howManyWords that takes as an argument a string s and returns the number of “words” in s.