learntheweb

String Methods

Introduction

We learned strings a few lessons ago, now it’s time to learn how to manipulate and change them! In this lesson we will be exploring some of the essential string methods in JavaScript. We will go over the substring, toUpperCase, toLowerCase, length, split, and replace methods. By the end of this lesson, you should have a better understanding of how to use these methods in order to manipulate strings. Let‘s get started!

Overview

By the end of this lesson, you should be able to:
    • Understand strings and how to use string indexes
    • Understand .length with strings
    • Understand .substring() in strings
    • Understand .toLowerCase() and .toUpperCase() in strings
    • Understand .split() and .replace() with strings

Strings?

Before learning about all the different ways we can manipulate and change strings here in Javascript, we first have to learn about the very basics of strings: indexes. String indexes might be a confusing topic to grasp for some, so here is a visual to understand what I mean when I say string indexes:

Let’s take a look at what’s going on. Each character in our string “Pastas” has an index assigned it, starting from 0 – 5. The reason why this is important is because most of the string methods you will learn today require you to use the indexes of strings. 

 

One important thing to notice is that our indexes, do not start at 1, but rather at 0. The very first character in a string is always marked with a string index of 0. From there, you count upwards by 1 until the end of the string. So how is this applicable? Take a look at this:

What’s happening here should start to make sense now. All we’re doing is calling the index that we want. If we wanted the first letter of the variable food, we would just say food[0]. Also note that our index will be wrapped in our brackets. In the next few sections, you will be learning about the different string methods that allow us to manipulate and change strings to our liking which can be helpful when you want to change data.  

Using .length() and .substring()

.length()

We can actually get the length of a string in Javascript with one simple method: .length! Here’s how it works:

let string1 = "Hello"
let string2 = "Random sentence I made up"
let string3 = ""

console.log(string1.length) // Logs 5
console.log(string2.length) // Logs 30
console.log(string3.length) // Logs 0

There’s not much to say about length. It’s a very simple, but powerful method that we can use here in JavaScript. In the unit where we go over for loops and while loops, we will learn how to iterate over lists and strings using the length method! And yes, you can use .length() to find the length of lists as well. With that out of the way, let’s move onto .substring()

.substring()

The .substring() method is a commonly used string method in JavaScript. It lets us extract a sequence of characters from a string, starting at a given start index and ending at a given end index. This method is useful for manipulating and extracting specific parts of a string. Here’s a visual that uses our previous example to explain how .substring() works.

Substring is very simple to understand. Basically, you are giving it two indexes and it will give the characters of the string from the first index to the last index. In the first example above, we are taking all the characters from string index 0 to the index 3 not including 3. That will give us “Pas”. 

 

Also make sure to notice that when we are creating a substring of a string, the last index has to be one higher than the desired ending position. This is because the last index is not included in the substring

 

Here is one last visual to help you understand:

Case Methods with Strings

Here in Javascript, there are a lot of case methods that we can use to change the way our strings look. The first ones we are going to talk about are the .toUpperCase() and the .toLowerCase() methods. Both methods allow us to change and manipulate our strings in some ways. Take a look:

// Using .toUpperCase()

let string = "Hello I am a String!"
console.log(string.toUpperCase()) 
// Logs "HELLO I AM A STRING!" to console

let sentence = "This is an example sentence."
console.log(sentence.toUpperCase())
// Logs "THIS IS AN EXAMPLE SENTENCE." to console
// Using .toLowerCase()

let string = "This Is Another String!"
console.log(string.toLowerCase())
// Logs "this is another string!" to console

let phrase = "This IS a Phrase With Multiple Words!"
console.log(phrase.toLowerCase())
// Logs "this is a phrase with multiple words!" to console

If you haven’t noticed by now, the toLowerCase and toUppercaseCase methods just turn the string fully uppercase/lowercase. So how would you be able to use this in a real situation? Let’s say you are asking for user input and if the user says “yes”, they move on to whatever is next. What if the user says “Yes” instead of “yes”? If we turned all the user input to lowercase using .toLowerCase()that would make it so regardless of which way the user says “yes”, it would be accepted as valid output.

Note:

    • When we are using methods like .toLowerCase() in our code, the capitalization matters a lot. Methods are NOT case sensitive and writing methods the incorrect way will lead to errors.
    • If you had written .tolowercase() instead of .toLowerCase(), this will cause an “error” within your code. Always make sure that the capitalization is properly written when using methods. 

Using .split() and .replace()

The last few methods we need to learn are .split() and .replace(). There are a TON more string methods throughout Javascript, but we are just covering the ones you might be using the most! Let’s start with .split()!

.split()

The .split() method is very simple by design. It will split a string into a list based on whatever character you assign it, let’s see how this looks in code:

// Example #1

let string = "Hello"
console.log(string.split("")) // Splitting string by character
// Logs "["H", "e", "l", "l", "o"]" in console
// Example #2

let text = "Basketball is awesome!"
console.log(text.split("s")) 
// Logs "["Basketball i", "awe", "ome!"]" in console
// Example #3

let numbers = "1-2-3-4-5-6"
console.log(numbers.split("-")) 
// Logs "["1", "2", "3", "4", "5", "6"]" in console

As you can see, the .split() method will split a string by the character that is specified in the string parameter. In the first example, we chose to split the string by every single character by not giving a value as a parameter. In the second example mentioned, we are splitting our string by every single space since that is what we specified. This can be very important if you want to split up a sentence of some sort. In the last example, we are splitting the entire string by the character 1. Any time the browser finds any instance of 1, it will split the string there.

 

.split() is a VERY powerful string method that is helpful to know. It’s very simple but you will most likely encounter a lot of situations where you want to use it.

.replace()

The .replace() method is another handy method we have in Javascript. It’s very simple to use. We give in an item to replace in a string/list, and then another item to replace it with. Here is how it works in action:

// Example #1

let string = "I love oranges!"
string = string.replace("oranges", "apples") // Replaces "oranges" with "apples"
console.log(string) // Logs "I love apples!"

In this example, we are taking our variable string and replacing the first instance of the word oranges with apples. Here is another example:

// Example #2

let string1 = "List methods are great!"
string1 = string1.replace("List", "String") 
string1 = string1.replace("great", "awesome") 
console.log(string1) // Logs "String methods are awesome!"

In this example, we first switched List with StringWe then swapped out great for awesome. The .replace() method is great for when you want to replace a certain character(s) in a String! Lists also have this functionality, but we’ll get into that in the next lesson!

Closing Note:

Although we covered numerous string methods in JavaScript, it is important to note that there are many more methods that were not discussed which could be beneficial for you to know. If you’re interested, you can refer to this full list of string methods available on w3schools.

 

Additional Resources:

    1. This youtube video goes over what we covered today along with some extra string methods
    2. If you want a more dictionary-like feel, once again check out the w3schools lesson on string methods!

As always, feel free to join our discord server if you need any help. We have a great community and people willing to help!

Practice

  1. Let’s learn string methods with a few simple exercises.
    1. Exercise #1
      1. Create a variable called string and give it the value I aM a StRiNg (Yes, it’s supposed to be weird)
      2. Create a variable called newstring that is the first four characters of our original string variable in all uppercase using the .substring() and .toUpperCase() methods.
      3. Now make another variable called anothernewstring that is the last four characters of our original string using the .substring() and .toLowerCase() methods.

    2. Exercise #2
      1. Create a variable called sentence and give it the value of String methods are really really awesome!
      2. First start by splitting it by all the spaces in the string.
      3. Next, split the variable sentence by all the letter e‘s throughout the sentence.
      4. Now, replace all occurrences of the letter a in a the sentence variable with the letter e using the .replace() method.

You should be all good now! If you’re itching for more practice, go to w3schools, they have tons of practice there!

Find an issue/typo/error with our content? Please report it here