Skip to content

Instantly share code, notes, and snippets.

@mmeigooni
Forked from rexfordkelly-at-makersquare/JS101_strings.js
Last active August 16, 2016 02:45
Show Gist options
  • Save mmeigooni/81210f7065f0cc4b1e067c3396f39fd3 to your computer and use it in GitHub Desktop.
Save mmeigooni/81210f7065f0cc4b1e067c3396f39fd3 to your computer and use it in GitHub Desktop.
/**
Number Exercises:
*/
/**
EXERCISE One: Enter the following expressions into your console.
*/
1 + 2
3 * 5
5 / 4 - 13
5000 * 234
1073 / 57 + 200
/**
EXERCISE Two: Why are the values produced by the following two expressions different? What are they?
*/
3 + 2 * 4 - 1
(3 + 2) * (4 - 1)
/**
EXERCISE Three: Calculate how old you are in minutes using the console.
*/
/**
EXERCISE Four: What is the percentage of people in the class with brown hair? Use the console to find out.
*/
/**
EXERCISE Five: Try the following expressions in the console:
*/
6 % 2
42 % 10
5 % 2
6 % 3
7 % 4
100 % 12
/**
What is the significance of the result? How does the % (modulus) operator work?
*/
/**
String Exercises:
*/
/**
Before we get started let's setup some data to play with.
*/
var yourName = 'YOUR_NAME_HERE'; // <-- Enter your name here.
var yourAge = 'YOUR_AGE_HERE'; // <-- Enter your age in number of years.
var yourFavoriteFood = 'SOMETHING_GOES_HERE'
var wordSet1 = 'The quick brown fox jumped over the lazy dog.';
var wordSet2 = 'Pack my box with five dozen liquor jugs.';
var wordSet3 = 'Jackdaws love my big sphinx of quartz.';
var wordSet4 = 'The five boxing wizards jump quickly.';
var wordSet5 = 'How vexingly quick daft zebras jump!';
var wordSet6 = 'Bright vixens jump; dozy fowl quack.';
/**
EXERCISE One: Concatenation
Concatenation is the process of joining one
or more strings together to form a new string.
PROMPT:
Using the variables yourName and yourAge
compose a sentence. Ensure you are using
the .concat() method.
*/
// A)
var newString = yourName.concat(' enjoyed some tasty ', yourFavoriteFood, ' on their ', yourAge - 1, ' birthday.');
console.log(newString) // We helped you out on this one.
// B)
// Compose your own string, using two or three of your own variables or strings
// C)
// Compose another string, which has numbers which are calculated within your expression
// D)
// Compose another string, which is composed of several smaller strings, which are spread out over 5 lines.
// E)
// the + operator allows us to concatenate strings in a simple manner
var anotherString = 'This string ' + 'was ' + 'created using the + ' + 'operator.';
// Redo A-D using the string's + operator.
// End of Exercise
/**
EXERCISE Two: String Inspection with .endsWith()
endsWith is a String method to test if a
string ends with another string. The value
the method returns is a boolean, true or false.
*/
// Usage:
var str = 'To be, or not to be, that is the question.';
console.log(str.endsWith('question.')); // true
console.log(str.endsWith('to be')); // false
/**
You can provide a third argument, to indicate/specify
your own "ending".
*/
console.log(str.endsWith('to be', 19)); // true
// A) Using endsWith compose an expression that returns a boolean value.
var userName = "John Doe";
var sirName = "Doe";
// Check if this person could be related to John Doe.
var personName = "Sally Doe Sue";
// your code here...
// Check if Dan could be related to John Doe.
var anotherPerson = "Dan Doe";
// your code here...
// Does this string contain the strings, swimming, and 30.
var someString = "Dan can go swimming, 30 min after he eats";
// B) fun with Phone Numbers
var areaCode = '818';
var number1 = '(818) 867 - 5309';
var number2 = '(323) 867 - 5309';
var number4 = '(310) 867 - 5389';
// write an expression that returns a boolean value
var areaCodeMatches1 = '';
var areaCodeMatches2 = '';
var areaCodeMatches3 = '';
// End of Exercise
/**
EXERCISE Three: .includes()
Well endsWith is pretty useful, but sometimes it can
feel a little awkward checking our strings.
Let's take a look at another method, ".includes()"
This handy method will allow you to search an entire
string for a match, and you don't need to know where
you want to start
*/
// Usage:
'Blue Whale'.includes('blue'); // returns false, it's case sensitive.
'Some words with the letter z'.includes('z') // returns true
/* There is a second argument you can provide .includes().
If you want to begin your search at a particular index
location of your string, simply pass that index to .includes()
as the second argument.
*/
'blah blah blah'.includes('blah', 4) // true
'This sentence contains the word, sentence, twice'.includes('sentence') // true
'This sentence contains the word, sentence, twice'.includes('sentence', 14) // true
// A) Complete the following so it works
var words = yourName + ' is learning some basic JavaScript, at the age of';
var hasAge = words.includes(yourAge); // notice, we can call .includes on a variable too.
console.log(hasAge);
// B) // fix this snippet so it console logs true/false based on an expression using includes.
var hasTheWordLearningInIt = false; // Replace this "false" with a string that works.
console.log(hasTheWordLearningInIt)
// C) Make your own examples of using .includes(). Make at least 3 examples.
// End of Exercise
/**
EXERCISE Four: inspecting strings with .indexOf()
Until now we have be manually inspecting our strings, it might be
useful to be able to inspect strings in a more abstract way.
.indexOf() is a method that will return to you the index of the
first match.
Unlike the above methods which return true or false, .indexOf()
will return a number. -1 if there are no matches or if there
was a match, the index of where the first match was found.
*/
'Blue Whale'.indexOf('Blue'); // returns 0
'Blue Whale'.indexOf('Blute'); // returns -1
/*
The .indexOf() method like the methods above, also accepts
an optional second argument. The second argument allows
you to provide an index, from which to start searching.
*/
'Blue Whale'.indexOf('Whale', 0); // returns 5
'Blue Whale'.indexOf('Whale', 7); // returns -1
/*
Tricky Tricky: If you search for an empty string ''
you will get some interesting results
*/
'Blue Whale'.indexOf('', 0); // returns 0
'Blue Whale'.indexOf('', 5); // returns 5
'Blue Whale'.indexOf('', 10); // returns 10
'Blue Whale'.indexOf('', 11); // returns 10
'Blue Whale'.indexOf('', 1000); // returns 10
// Notice how we only got 10 as output for the last two.
// This is because the last index of the string is 10
// A) Working with Indexes, find the index of the first "e" within this words variable using .indexOf(), save it to a variable
var words = "She sells sea shells down by the sea shore";
// B) Using the variable you just made, check and see if there is a second e somewhere in the string
/* C) Playing with Legos:
Keep building up new variables each with the index of the next e in the words string.
Then using those variables, to build a new string, where each letter is the letter 1 before
each variable's index.
Example:
words: 'the quick brown fox jumped over the lazy dog'
- - -
result: 'hpv'
*/
var words = 'the quick brown fox jumped over the lazy dog';
var eOne = words.indexOf('e');
var eTwo = words.indexOf('e', eOne + 1);
var eThree = words.indexOf('e', eTwo + 1);
console.log(words[eOne -1] + words[eTwo -1] + words[eThree-1] )
// Now you try:
var words = "She sells sea shells down by the sea shore";
// And one more
var words = "somewhere over the rainbow bluebirds fly";
/*
Great Job! that was a little more complicated, but you pulled through!
*/
// End of Exercise
/**
EXERCISE Five: Playing Simon Says, with .repeat()
.repeat() is a simple method, it will construct a new string
with the original string repeated n number of times.
*/
var myString = 'abc';
var str = myString.repeat(-1); // RangeError, the number of times should be 0 or more
var str = myString.repeat(0); // ''
var str = myString.repeat(1); // 'abc'
var str = myString.repeat(2); // 'abcabc'
var str = myString.repeat(3.5); // 'abcabcabc' (count will be rounded down)
// a) Complete the lyrics of this song
var start = 'the wheels on the bus go ';
var hook = 'round and round ';
var end = ' all day long.';
// this should read "the wheels on the bus go round and round, round and round, round and round, all day long"
var completed;
// b) 60's batman intro
var hook ="Na, "
var who = "batman"
// should read "NA NA NA NA NA NA NA NA NA NA NA NA NA NA BATMAN!!!"
var batmanIntro;
// End of Exercise
/**
EXERCISE Six: .slice( beginAt, endAt )
.slice() allow you to copy, a section of a string.
Parameters
beginSlice
The zero-based index (indexes start at 0) at which to begin extraction.
If negative, it is treated as totalLength - your negative beginSlice
(for example, if beginSlice is -3 it is treated as totalLength - 3),
*/
var someString = "the quick brown fox jumped over the lazy dog.";
var someSubString = someString.slice(-4); // "dog."
/*
endSlice
Optional. The zero-based index (indexes start at 0) at which to end extraction.
If omitted, slice() extracts to the end of the string. Like beginSlice, if this
"endSlice" is negative, it would be treated as if your wrote totalLength minus
you specified amount.
*/
var anotherSubString = someString.slice(-4, -1); // "dog"
/*
invoking .slice() will return your specified substring or an empty string ''
if nothing was found
slice() extracts up to but not including endSlice. str.slice(1, 4) extracts
the second character through the fourth character (characters indexed 1, 2, and 3).
As an example, str.slice(2, -1) extracts the third character through the
second to last character in the string.
*/
// Using the text in the someString variable above and .slice() re-arrange the text to
// make 3 new sentences.
var sentenceOne;
var sentenceTwo;
var sentenceThree;
// Perfect, now join all three of these sentences into a new paragraph, and make a new sentence
// one with all the "the" words removed.
var noTheWordsInString;
// Ok now make a new sentence, only this time, switch out the word "fox" for "elephant", and
// the word "lazy" to brave. Then go back and add all the "the" words back.
// Good Job!!!
// End of Exercise
/**
EXERCISE Seven: .startsWith(), Inspecting Strings, from the beginning.
.startsWith( searchString, fromWhere )
searchString:
The characters to be searched for at the start of this string.
fromWhere:
Optional. The position in this string at which to begin searching for searchString;
defaults to 0.
*/
var str = 'To be, or not to be, that is the question.';
console.log(str.startsWith('To be')); // true
console.log(str.startsWith('not to be')); // false
console.log(str.startsWith('not to be', 10)); // true
/**
*/
// End of Exercise
/**
Oh boy! that was a whole bunch of keyboard punching. That's pretty much it for todays
exercise plan.
There is one more method you should learn about, if you have the time. For this one I
will point you to a resource where you can learn about it on your own.
Once you have a handle on it, review the above exercises and see if you can adopt one
or two exercises to solve using this new method.
Let's learn about the .trim() method. Go to [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim]
poke around, and see how it's used, there should be example on that page as you scroll down.
Play around with the method. What happens if there are spaces before letters? After? In between? Where would a method like trim be useful?
*/
/**
Still hungry? Awesome! Let's get a head start on next class.
Check out [http://this.reactorprep.com/intro-functions]. Browse through the slides independently and give the exercises at the bottom a shot.
*/
/**
The website I gave you above is a super useful reference for almost everything JavaScript. Bookmark
it as we will be going back tomorrow.
// End of Exercise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment