Strings
We declare strings by using either single or double quotes.
Suppose we need to write a quote as part of our string. We can use either the other kind of quote or we can use the backslash '\'. When we use the backslash its called "escaping" the symbol. It tells the computer that the next character should be treated as a character and not as a quote of any kind. Its used in many other situations.
Here is a list of the special characters that can be added using the backslash.
Suppose we want to know the length of the strings in the previous examples.
Notice that the operator '+' concatenates strings.
Here are the commands you can use with strings
A very useful function is indexOf which returns the position of the charcter in the string. You can specify several and it gives the postion of the first one.
What do you think lastIndexOf returns? Try it in the code below.
The command 'split' can also divide the string at a given letter.
Another useful function is split which takes a string and breaks it into an array. So now we see that arrays in Javascript can hold any kind of type. Arrays are one of the basic storage types in Javascript and we will make much use of them.
Active Learning - Hand this in.
It is said that a monkey, given a typewriter and enough time, will eventually type out the works of William Shakespeare. We are going to simulate that monkey. Since our monkey can't yet type we will give it a bag of letters to pick from. The monkey reaches into the bag and picks out letters one by one.
The 'target' is the phrase we want the monkey to type. The 'start' is the string of letters in the bag - from this we create the array 'bag' full of the letters. Once a letter is picked we remove it by making it 'null' in the array.
Change the code in 'removeFromBag(bag, index)' so you actually remove the letter from the array 'bag' so that the length of 'bag' is now smaller.. You will also have to change 'getRandomLetter(bag)' since the size of the array 'bag' has now changed. Once you have it working see how long it takes the monkey to produce the phrase 'to be or not'. What is the increased complexity of the problem for the monkey to produce the phrase 'to be or not to be'?