const - JS | lectureData Structures, Modern Operators & Strings

Working with Strings - Part 1

Data Structures, Modern Operators & Strings

Over the next few lectures, we will learn how to work with strings, and we're going to be looking at a couple of useful string methods. Let's get started!

Let's start by creating a variable called airline and assigning it the value "United Airlines".

script.js
const airline = 'United Airlines';

Now let's create a variable called plane and assign it the value "A320".

script.js
const plane = 'A320';

Let's now do some stuff with these variables. Just like in arrays, we can get the character of a string at a certain position.

script.js
console.log(plane[0]); // A
console.log(plane[1]); // 3
console.log('B737'[0]); // B

We can also get the length of a string just like we did with arrays.

script.js
console.log(plane.length); // 4
console.log('B737'.length); // 4

Next up, let's talk about string methods. So again, comparing strings to arrays here, strings also have methods, and some are quite similar to the array methods. The first one we'll look at is indexOf. This method gives us the position of a certain character in a string.

script.js
// Keep in mind that the index starts at 0

/**
 * When searching for words with indexOf, you have to keep in mind that it is case sensitive.
 *
 * For example, if you search for the word "hello" in the string "Hello, World!", it will return -1.
 */
console.log(airline.indexOf('United')); // 0

console.log(plane.indexOf('3')); // 1
console.log(plane.indexOf('A')); // 0

The indexOf method gives us the first occurence but sometimes we want to get the last occurence. And for that, we can use the lastIndexOf method.

script.js
console.log(airline.lastIndexOf('i')); // 11
console.log(plane.lastIndexOf('3')); // 1
console.log(plane.lastIndexOf('A')); // 0

You are surely asking yourself, what can we do with these indexes? Why are they useful? Well, one good use case is to extract part of a string using the slice method, and the slice method needs indexes as arguments. And so therefore, sometimes, it can be very useful first to figure out the index of part of a string to then extract that. Let's see how the slice method works.

script.js
/**
 * By doing `airline.slice(4)`, we are extracting the string from index 4 to the end of the string.
 *
 * U n i t e d   A i r ...
 * 0 1 2 3 4 5 6 7 8 9 ...
 *
 * The extracted string is usually called a substring.
*/
console.log(airline.slice(4)); // ed Airlines

Keep in mind that this does not change the underlying string. It just returns a new string. That's because, it's actually impossible to mutate strings. They are primitives. So it we wanted to use the result of the above slice method, we would have to store it first in some variable or some data structure.

Now, besides the start index or parameter that we already specified, we can also specify an end index. Let's try it out.

script.js
/**
 * By doing `airline.slice(4, 8)`, we are extracting the string from index 4 to index 7. The end index is not included.
 *
 * U n i t e d   A i r ...
 * 0 1 2 3 4 5 6 7 8 9 ...
 *
 * The length of the extracted string is always going to be end - start.
*/
console.log(airline.slice(4, 8)); // ed A

Now up until this point, we have always just hard-coded the indexes. But of course, many times, we don't even know the string we receive yet. Hence, let's now try to extract the first word in the airline string without knowing any of the indexes. And so that's where indexOf and lastIndexOf become useful.

script.js
/**
 * We want to extract the first word in the string. This means that we need to slice the string from index 0 to the first space.
 *
 * If we had a string like "Hey My Friend", it would be "Hey". Becaue we are slicing from index 0 to the first space, we are not including the space. And remember that indexOf returns the first index of the character we are looking for.
*/
console.log(airline.slice(0, airline.indexOf(' '))); // United

If we wanted to extract the last word in the string, we can use the lastIndexOf method.

script.js
/**
 * We are doing airlin.lastIndexOf(' ') + 1 because we don't want to include the space.
 *
 * With this example doing also airline.slice(airline.lastIndexOf(' ') + 1) would be the same as doing airline.slice(airline.indexOf(' ') + 1) because the space character is only present once.
 *
 * But just like before, if we had a string like "Hey My Friend", we need to use the lastIndexOf method to get the last index of the space.
*/
console.log(airline.slice(airline.lastIndexOf(' ') + 1)); // Airlines

That's the fundamentals of the slice method, but we can do even more with it. We can specify a negative start index, and that will mean that we start counting from the end of the string. Let's try it out.

script.js
console.log(airline.slice(-4)); // ines

We can also specify a negative end index. Let's try it out.

script.js
console.log(airline.slice(4, -1)); // ed Airline

It's now time to practice what we have learned. Le'ts create a function that receives an airplane seat and logs to the console whether it is a middle seat or not.

script.js
function isMiddleSeat(seat) {
  const s = seat.slice(-1);

  if (s === 'B' || s === 'E') {
    console.log(`${seat} is a middle seat.`);
  } else {
    console.log(`${seat} is not a middle seat.`);
  }
}

isMiddleSeat('11B'); // 11B is a middle seat.
isMiddleSeat('23C'); // 23C is not a middle seat.
isMiddleSeat('3E'); // 3E is a middle seat.

Before we move on to the next lecture, let's just stop for a second and understand why all of this works. We know that strings are just primitives. But why do they have methods? Shouldn't methods only be available on objects such as arrays?

Well, that's true. However, JavaScript is really smart. Here is how it works. Whenever we call a method on a string, JavaScript will automatically, behind the scenes, convert that string to an object with the same content. And then it's on that object where the methods are called. This process is called boxing because, it takes our string and puts it into a box which is the object.

This is what JavaScript does:

script.js
console.log(new String('Hello'));

WWS - 1

You can see from the aboe image that the string looks a little bit more like an object. And in the [[Prototype]] section, you can see a list of methods, like indexOf that we just used. But this is beyond the scope of this lecture.

We will learn more about this later. What matters is that new String('Hello') is now an object.

script.js
console.log(typeof new String('Hello')); // object

The above conversion is what JavaScript does behind the scenes whenever we call a method on a string. And then, when the operation is done, the object is converted back to a regular string primitive.

Note that all string methods return primitives. Even if called on a string object.

script.js
console.log(typeof 'Hello'.toUpperCase()); // string
console.log(typeof new String('Hello').toUpperCase()); // string

Let's now move on to the next lecture and continue working with strings.