String Methods — JavaScript

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…

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

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"

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

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"
  1. split("") gives ["m", "i", "l", "k"].
  2. .reverse() reverses the order of that array, to ["k", "l", "i", "m"].
  3. .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?

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.

What you will learn