2.5 - "Strings"
Review
for-loops help us to iterate through values (count and loop in a sequential order)
let answer = 0;
// Add 1+2+3+4+5+6+7+8+9+10
for (let index = 1; index <= 10; index++) {
answer += index;
}
console.log(answer); // 55
Recall: Computers only know numbers, written in binary. So how do we see letters or type a document?
Mr. Squirrel's Joke of the Day
"Today I learned that if you turn a canoe over, you can wear it as a hat.
Because it's capsized!"
If today's lesson doesn't quite make sense, check out lessons 18 to 23 here.
Today's Lesson: "Strings"
A single letter is called a character (char).
Each character is a symbol (drawing) with a number behind it. The computer looks-up the symbol, based on the number.
Many characters together is called a String of characters. Like a string of Christmas lights.
For Example: The word hello is a string made of the chars 'h' 'e' 'l' 'l' 'o'.
A char is primitive. They're very boring. Not much we can do with them.
A String is an object. Lots of neat properties and functions available to them.
Note: JavaScript treats single letters as a String, not a char.
Properties and Functions
It is very important to remember that "a" and "A" are considered different. "Hello" != "hello"
A property is a fact about that object or thing.
Strings have a very important property: length
let myString = "Hello World!";
console.log(myString.length); // Prints 12 to the screen
A function - also known as a method - is something that an object can do or give or utilize to manipulate data or give a result.
Strings have lots of useful functions but the ones we might focus on are:
.charAt()
.toUpperCase() and .toLowerCase()
.charCodeAt()
.substring()
and many more, with awesome examples at w3schools!
Extracting & Changing Characters
There is a shortcut to the charAt() method for finding a char at a specific location:
Square brackets with a location (index): "Hello World"[6] will return 'W'
let text = "My name is Mr. Squirrel";
console.log(text.length); // 23
console.log(text[1]); // y
console.log(text[23]); // undefined
Now that we know for-loops, we can loop through a string!
let longText = "Supercalifragilisticexpialidocious";
for (let letter = 0; letter < longText.length; letter++) {
console.log(longText[letter]);
}
Strings are immutable. This means you cannot modify a single character without destroying and recreating the memory space.
let text = "My name is Mr. Squirrel";
text[3] = "Z"; // This does nothing
3.4 Task(s) / Homework
Complete the project in Replit: 3.4 - Strings: There and Back Again