Someone types their email into a login form: " [email protected] ". Spaces were typed by accident at the front and the back, and the letters are a mix of capital and small. The stored email is "[email protected]". If you compare the two as they are, they don't match, even though it is the same person. So the typed text has to be cleaned first: remove the spaces and make the letters small.
JavaScript already gives you the tools: string methods, built-in commands that you can use on any string to work with text. There are methods to change letters, to search, to cut and to replace. To call a method, write the string, a dot, the method's name, then parentheses. The result is always a new value. The original string doesn't change.
Calling a method
This code calls the method toUpperCase on text, then prints the result and the original string:
const text = "Learning JavaScript";
const result = text.toUpperCase();
console.log(result); // LEARNING JAVASCRIPT
console.log(text); // Learning JavaScript
text.toUpperCase()means: take the string intext, then run the methodtoUpperCase(change to capital letters) on that string. The parentheses()are what run the method, so you must write them.- The method returns (gives back) a new string, stored here in the variable
result. textstays as it was:console.log(text)still printsLearning JavaScript, not the version in capitals. In JavaScript the contents of a string can't be changed, so every method makes a new string. If you want to keep the result, put it in a variable:const result = text.toUpperCase();.
Methods you'll use a lot
The comment on the right shows the value each line returns:
"hello".toUpperCase() // "HELLO"
"HELLO".toLowerCase() // "hello"
" hello ".trim() // "hello"
"Learning JS".includes("JS") // true
"Learning JS".includes("js") // false
"Good Morning".slice(0, 4) // "Good"
"a-b-a".replace("a", "X") // "X-b-a"
"a-b-a".replaceAll("a", "X") // "X-b-X"
toUpperCase()turns every letter into a capital letter,toLowerCase()into a small letter.trim()removes the spaces at the start and the end of the text. Spaces in the middle stay.includes("JS")givestrueif the text contains"JS". Capital and small letters are checked too:"js"in small letters is not found.slice(0, 4)takes the piece of text from position 0 up to just before position 4. Letter positions (indexes) are counted from 0, so you get the first four letters.- In
replaceandreplaceAll, the first value in the parentheses is the text to look for, and the second is its replacement.replaceonly replaces the first match.replaceAllreplaces every match.
Cutting text up with split
This code cuts one sentence into its words:
const sentence = "we love coffee";
const words = sentence.split(" ");
console.log(words); // ["we", "love", "coffee"]
console.log(words.length); // 3
split(" ")cuts the text at every space and gives back an array (a list of values)..lengthon an array gives the number of items in it. So the number of words in a sentence issentence.split(" ").length. On a string,.lengthcounts characters (letters, and spaces too), not words.split(""), with empty quote marks, cuts between every letter:"milk".split("")gives["m", "i", "l", "k"].
Chaining methods: reversing text
A string has no method to reverse the order of its letters, but an array does. So you cut the text into an array first, reverse that array, then join its items into a string again:
"milk".split("").reverse().join("") // "klim"
split("")gives["m", "i", "l", "k"]..reverse()reverses the order of that array, to["k", "l", "i", "m"]..join("")joins the array's items into one string with nothing between them:"klim".
Methods chained like this run from left to right. Each method works on the result of the method before it.
If the text has an emoji in it, this way of reversing breaks the emoji: split("") cuts one emoji into two parts that cannot be shown.
In the exercises, methods are used inside a function. Without return, a function gives undefined. So it looks like this: the data comes in through the parameter (the name inside the function's parentheses), and the result is given back with return:
function shout(text) {
return text.toUpperCase() + "!";
}
console.log(shout("hello")); // HELLO!
⚠️ Why isn't the method doing anything?
- Forgetting the parentheses.
text.toUpperCasewithout()doesn't run the method. - Misspelling a method's name.
revers()ortouppercase()causes anis not a functionerror, because no method has that name. Method names are case-sensitive:toUpperCase, with a capital U and C. - Expecting the original string to change. Keep the method's result in a variable, or give it back right away with
return.
TL;DR: String methods are built-in commands for working with text. You call a method with text.methodName(), and it always returns a new value, while the original string stays the same. toUpperCase() and toLowerCase() change letters to capital or small, and trim() removes spaces at the start and the end. includes() checks whether the text contains another text, slice() takes a piece, replace() and replaceAll() replace part of the text. split(" ") cuts text into an array (a list) of words, and .length counts the items in that array. To reverse text: split("") (cut into letters), reverse(), then join("") (join again). Inside a function, work on the parameter (the data that comes in) and give back the result with return.
⚡ A method gives a new string
Write:
const text = "Learning JavaScript";
const result = text.toUpperCase();
console.log(text);
Guess first: what does console.log(text) print?
Still Learning JavaScript, not capitals. Only result holds the capitals.
Meaning: text.toUpperCase() runs the method toUpperCase (a built-in command that changes text to capital letters) on the string in text, and gives back a new string. The original string doesn't change, so keep the result in a variable. You must write the parentheses (), because they are what run the method.
⚡ Tidy, search, cut
Write:
" hello ".trim() // "hello"
"Learning JS".includes("js") // false
"Good Morning".slice(0, 4) // "Good"
Meaning: The comment on the right shows the result of each line. trim() removes the spaces at the start and the end of the text. includes() checks whether the text contains the value in the parentheses. Capital and small letters are checked too, so "js" is not found. slice(0, 4) takes the piece from position 0 up to just before position 4. Letter positions are counted from 0, so the result is the first four letters.
⚡ Cut, reverse, join
Write:
"milk".split("").reverse().join("") // "klim"
Guess first: do strings have a method to reverse text?
No, but arrays (lists of values) do. So the text is turned into an array first.
Meaning: Chained methods run from left to right, and each method works on the result of the one before it. split("") cuts the text into an array of letters, reverse() reverses their order, and join("") joins them into a string again. split(" ") with a space cuts text at every space, and .length on the resulting array counts the words.