Javascript Exercises

For this set of exercises, use JsFiddle. You can write pure Javascript in the lower-left corner. To see your answers rendered on the right-hand side, use the method console.log(returnValue);. Then, click "Console" in the lower-right hand part of the screen.

Operators and Inequality

Which of the following is a valid operator for testing inequality in Javascript?

A. ne
B. !==
C. is not
D. =/=
E. -=

Variables

Write a line of Javascript code which declares a variable called "total" and assigns it the value 0.

String-List

Write code for the two functions:

1. digitList(s): Given string s. Return an array of the int values of the digit chars in s, so "ab31xx41" returns [3, 1, 4, 1]. parseInt may be useful. Additionally, to help you, use this helper function which returns true if the passed-in character is a digit, and false otherwise:

function isDigit(character) {
    /* This function uses a regular expression to check if the character is a digit.

       If you don't know what a "regular expression" is, don't worry about it!  All 
       you need to know is that this function returns a boolean depending on whether 
       the character is a digit.
    */
    return /^\d+$/.test(character);
}

2. atly(s): The string s will contain either zero or two or more '@' chars. If there are two or more '@', return a string made of the chars after the second '@' followed by the chars before the first '@'. So "aa@bbb@cccc" returns "ccccaa". If there are no '@' return null. string.indexOf() will be helpful!

function digitList(s) {
    // your code here
}
function atly(s) {
    // your code here
}

Objects: Counting Strings

Given an array of word strings, compute and return a "counts" object that has a key for each distinct word, and its value is the number of times that word occurs.

function countStrs(strs) {
    // your code here
}

Objects: Counting Characters

Given a string s. Return a counts dict with a key for every distinct char in s (lowercase form), and the value is the number of times that char appears in s. e.g. 'Coffee' returns {'c': 1, 'o': 1, 'f': 2, 'e': 2}

function countChars(s) {
    // your code here
}