const - JS | lectureData Structures, Modern Operators & Strings

Working with Strings - Part 2

Data Structures, Modern Operators & Strings

Let's continue with some simple string methods. The first two methods we will work with will be for changing the case of a string. These methods are: toUpperCase() and toLowerCase().

To try it out, let's cretat another airline variable and assign it a value of "American Airlines".

script.js
/**
 * Both methods do not take any arguments.
 */
const airline = 'American Airlines';
console.log(airline.toUpperCase()); // "AMERICAN AIRLINES"
console.log(airline.toLowerCase()); // "american airlines"

You can call these methods directly on a string like this:

script.js
console.log('Mike'.toUpperCase()); // "MIKE"

Let's now use these methods to fix the capitalization issue in a passenger's name. Let's say that when he checked in, the passenger misspelled his name, so it looks like this now:

script.js
// Misspelled name
const name = 'mIkE';

// Correct name ==> "Mike"

To fix this capitalization issue, the first step is usually to put everything in lowercase.

script.js
console.log(name.toLowerCase()); // "mike"

By doing this, we can notice that we already have the last three letters. All that's left now is to take the first letter and then the rest of the string and put these two parts back together.

script.js
/**
 * To get the first letter you can either user:
 * 1. `name.slice(0, 1)`
 * 2. `name[0]`
 *
 */
const nameLower = name.toLowerCase();
const firstLetter = nameLower.slice(0, 1);
const remainingLetters = nameLower.slice(1);
console.log(firstLetter.toUpperCase() + remainingLetters); // "Mike"

Let's now do another real-life example, which is to compare emails. Let's say we have the email of a passenger which is:

script.js
const email = 'mike@constjs.dev';

But now when the passenger tries to log in, he does it all wrong, and ends up with the following email:

script.js
const loginEmail = '  Mike@CoNsTjS.deV \n';

The log in email (Mike@CoNsTjS.deV) is still kind of correct and valid. So we can now still compare if the emails are the same. So we can now try to convert loginEmail to email and then check if they are the same because essentially they are.

They would be different if we had different letters in loginEmail, then, of course they would be different. But here, it's just a matter of capitalization. For emails, I believe they are still valid even with capitalization off.

Again, when we check user input like this, the first step is usually to convert everything to lowercase.

script.js
const loginEmaiLower = loginEmail.toLowerCase(); // '  mike@constjs.dev \n'

We now need to get rid of all the spaces. And the method for this is: trim().

script.js
/**
 * Remember that \n is a new line character and also counts as whitespace.
 */
const loginEmailTrimmed = loginEmaiLower.trim(); // 'mike@constjs.dev'

We can now see that it looks exactly the same as the original email. Before moving on, let's have a closer look at what we did. We called the method toLowerCase() on the loginEmail variable and stored the result in loginEmaiLower. Then, we called the method trim() on the loginEmaiLower variable and stored the result in loginEmailTrimmed. But why do we even need all those intermediate variables? We could do all this in one step.

script.js
/**
 * loginEmail.toLowerCase() returns a string, and on strings we can call string methods.
 */
const correctEmail = loginEmail.toLowerCase().trim(); // 'mike@constjs.dev'

For the sake of completion,let's compare correctEmail to email.

script.js
console.log(correctEmail === email); // true

Since ES2019, there is also trimStart() and trimEnd(), which as their names say, you can use to trim whitespace from the start or end of a string. Next up, let's learn one o the most important things about strings, which is to replace parts of strings.

Let's say we have the price of a flight, and that price is for Paris.

script.js
const priceParis = '350,89€';

Let's now try to compute the price in USD. That is, we need to replace the euro symbol with the dollar symbol, and the comma separator with a dot. TO do this, we can use the replace() method.

script.js
/**
 * The replace() method is case sensitive.
 *
 * The replace() method takes two arguments:
 * 1. The string to replace
 * 2. The string to replace it with
 *
 */
const priceParisUsd = priceParis.replace('€', '$').replace(',', '.');
console.log(priceParisUsd); // '350.89$'

We can also replace entire words, not just characters. Let's say we have the following string:

script.js
const announcement =
  'Passengers, please check in at the door. Please be on time.';

Now let's try replacing the word door with the word gate.

script.js
console.log(announcement.replace('door', 'gate')); // 'Passengers, please check in at the gate. Please be on time.'

Keep in mind that the replace() method only replaces the first instance of the string. Consider the below example:

script.js
const text =
  'Please check the door, and if there is no one, please close the door.';

If we try to replace the word door with the word gate, we will get the following result:

script.js
console.log(text.replace('door', 'gate')); // 'Please check the gate, and if there is no one, please close the door.'

You can see the the word door was replaced only once. If we want to replace all instances of door, we can use the replaceAll() method.

script.js
console.log(text.replaceAll('door', 'gate')); // 'Please check the gate, and if there is no one, please close the gate.'

Another solution to replace all instances of a string is to use something called a regular expression. Regular expressions are one of the most complex and confusing programming topics, but we will still take a short look at them at some point in the sourse. But for now, we are just going to use a very simple regular expression to tell the replace() method that it should target all the occurences of door and not just the first one.

script.js
/**
 * The g flag in our regular expression stands for global.
 *
 * This means that we want to replace all instances of `door` with `gate`.
 */
console.log(text.replace(/door/g, 'gate'));

To finish this lecture, there are three string methods that return boolean values: startsWith(), endsWith(), and includes(). Let's take a look at each of these methods.

script.js
const plane = 'E190PL';
console.log(plane.includes('E190')); // true
console.log(plane.includes('A320')); // false

console.log(plane.startsWith('Airbus')); // false
console.log(plane.startsWith('E190')); // true

Let's consider another plane variable:

script.js
const plane2 = 'Airbus A380neo';

Now, let's say we want to check if this plane is part of the Airbus brand.

script.js
if (plane2.startsWith('Airbus') && plane2.endsWith('neo')) {
  console.log('This plane is part of the Airbus brand.');
} else {
  console.log('This plane is not part of the Airbus brand.');
}

So whenever you need to take some descisions based on the content these three methods are very helpful. Let's finish with a practice exercise.

Let's write a function that checks if the baggage of a passenger is allowed to check in.

script.js
const checkBaggage = function (baggageItems) {
  /**
   * When receiving input from the user, always convert it to lowercase.
   * It makes it easier for comparison, because remember string methods
   * like `includes()` are case sensitive.
   */

  const baggageItemsLower = baggageItems.toLowerCase();

  /**
   * If the baggage items contains the word `knife` or `gun`, then the baggage is allowed on board.
   */

  if (
    baggageItemsLower.includes('knife') ||
    baggageItemsLower.includes('gun')
  ) {
    console.log('You are NOT allowed to carry a knife or a gun.');
  } else {
    console.log('Welcome on board!');
  }
};

checkBaggage('laptop, food, knife'); // 'You are NOT allowed to carry a knife or a gun.'
checkBaggage('socks, Camera'); // 'Welcome on board!'
checkBaggage('sNacks, nintendo'); // 'Welcome on board!'
checkBaggage('gun, cake, Chemicals'); // 'You are NOT allowed to carry a knife or a gun.'