menu-button

String Manipulation

Task #1: Goodbye First and Last

Write some code that removes and first and last character of the string. e.g. noFirstLast("monkey") would output onke. The last line of code within the function should start with return, e.g. return "My String"; would output the value "My String".

Reset to Original Code     Fullscreen

Task #2: Total length of strings in an array

Write some code that uses an array of strings (the variable strs), and outputs the total length of the string. Can you do it in a single line of code?

Reset to Original Code     Fullscreen

Task #3: Capitalising each word

Write some code that inputs a string (the variable str) and outputs a string where each word has the first letter capitalised (and the remaining letters unchanged). For example capitaliseWords("stephen king") would output "Stephen King". Hint: You may want to consider using the split function for strings, as well as a for loop. It's however possible to do the whole thing in one line of code!

Reset to Original Code     Fullscreen

Task #4: Secret Code

Write some code that 'encrypts' a string by replacing each character with the one immediately after. e.g. 'b' would be replaced with 'c', 'T' would be replaced with 'U', and so on.

The first variable str is the string to encrypt/decrypt. The second variable reverse is a boolean variable, which is false if we want to encrypt the string, and true if we want to decrypt it (i.e. retrieve the original string).

It will be helpful to use the string function charCodeAt(i) would gets the equivalent 'numeric value' of the character at position i in the string. For example "a".charCodeAt(0)" gives 97, and "b".charCodeAt(0)" gives 98. Similarly String.fromCharCode(97) converts 97 back into "a".

Reset to Original Code     Fullscreen

Task #5: Name Replacer

Write some code that replaces each of NAME1, NAME2 and so on within str with the names provided in the array names. So nameReplacer("NAME1 and NAME2", ["Adam","Eve"]) would output "Adam and Eve".

Reset to Original Code     Fullscreen

Task #6: Find all occurrences

The string function str.indexOf(substr) finds the position of the first occurrence of substr within str. For example, "Apple".indexOf("pp") would output 1. An optional second argument allows us to specify the position we start looking from, for example, "Banana".indexOf("na", 3) would output 4, because the first occurrence of "na" occurs at position 2 (remembering we start counting from 0), but we started searching from position 3.

Code a function indexOfAll which searches for all occurrences of b within a, and returns an array of all the matching positions in ascending order. For example indexOfAll("Banana", "na") would return [2,4].

Reset to Original Code     Fullscreen