const - JS | lectureData Structures, Modern Operators & Strings

Working with Strings - Part 3

Data Structures, Modern Operators & Strings

This is the third and final part of the series on working with strings. Let's start by learning about one of the most powerful string methods: .split(). The .split() method takes a string and splits it into an array of strings based on a divider string.

Lets take a look at an example:

/**
 * The divider string in this example is the plus sign.
 */
const str = 'A+very+long+string+to+split';
const arr = str.split('+');
console.log(arr); // [ 'A', 'very', 'long', 'string', 'to', 'split' ]

Let's have another example:

/**
 * The divider string in this example is the space character.
 */
const str = 'John Doe';
const arr = str.split(' ');
console.log(arr); // [ 'John', 'Doe' ]

The .split() method returns an array of strings, giving us the possibility to use the power of destructuring to easily access the individual strings.

const str = 'John Doe';
const [firstName, lastName] = str.split(' ');
console.log(firstName); // John
console.log(lastName); // Doe

We could have done the same thing with the slice() method, but that would hae been a lot more complicated and, for longer sentences, almost impossible.

Now, let's say we want to make the lastName uppercase and, we also want to add a mister in the beginning. The easiest way to do this would be to use a template literal, but I want to show you something else here. And that's the join() method which is essentially the opposite of .split().

Let's have a look at an example:

/**
 * Just like the `.split()` method, the `.join()` method receives a divider string as a parameter, which in this case is the space character.
 */
const name = ['Mr.', firstName, lastName.toUpperCase()].join(' ');
console.log(name); // Mr. John DOE

We can use this to do something we've already done in one of the previous lectures, which is to capitalize a name. Let's have a look at an example.

Let's say we want to capitalize the first letter of each name of the below passenger names.

const passenger = 'nelson fox gilbert bowman';

/**
 * Final result: Nelson Fox Gilbert Bowman
 */

Well, let's start by creating a function called capitalizeName that takes the passenger's names as a parameter.

function capitalizeName(names) {}

Knowing that we have multiple names in a name and that we have to capitalize the first letter of each name, it will be good to have them inside of an array that we can then loop over.

function capitalizeName(name) {
  const passengerNamesSplit = names.split(' ');
}

Let's now loop over the passengerNamesSplit using the for of loop, and capitalize the first letter of each name.

function capitalizeName(names) {
  const passengerNamesCapitalized = []; // Variable to store the capitalized names
  const passengerNamesSplit = names.split(' ');

  for (name of passengerNamesSplit) {
    passengerNamesCapitalized.push(name[0].toUpperCase() + name.slice(1));
  }
}

To finish our function, let's join the passengerNamesCapitalized array back into a string and return it.

function capitalizeName(names) {
  const passengerNamesCapitalized = []; // Variable to store the capitalized names
  const passengerNamesSplit = names.split(' ');

  for (name of passengerNamesSplit) {
    passengerNamesCapitalized.push(name[0].toUpperCase() + name.slice(1));
    /**
     * You can also use the `replace()` method to capitalize the first letter of each name.
     *
     * passengerNamesCapitalized.push(name.replace(name[0], name[0].toUpperCase()));
     */
  }

  return passengerNamesCapitalized.join(' ');
}

You can now give it a try.

const passenger = 'nelson fox gilbert bowman';
console.log(capitalizeName(passenger)); // Nelson Fox Gilbert Bowman

Next, let's talk about padding a string. Padding is a way to add characters to the beginning or end of a string until the string reaches the desired length. Let's have a look at an example.

const str = 'Hello';
/**
 * THe `padStart()` method takes two arguments:
 * - The desired length of the string (After the padding)
 * - The character to pad with
 */
const paddedStr = str.padStart(10, '-');

console.log(paddedStr); // -----Hello
console.log(paddedStr.length); // 10

console.log(paddedStr.padEnd(15, '-')); // -----Hello-----

Let's now see a real world example of padding. When you see a creedit card number on the internet, you never see the entire number. Usually, we see the last 4 digits, and the rest is masked with some symnbols.

Let's implement a function that does exactly that.

function maskCreditCard(cardNumber) {}

We will start by converting the cardNumber into a string.

function maskCreditCard(cardNumber) {
  const cardNumberStr = String(cardNumber);
}

Now, let's extract the last 4 digits of the cardNumberStr and store them in a variable called last4Digits.

function maskCreditCard(cardNumber) {
  const cardNumberStr = String(cardNumber);
  const last4Digits = cardNumberStr.slice(-4);
}

We now need to return the last4Digits variable, padded at the beginning with *, all the way until the original length of the string.

function maskCreditCard(cardNumber) {
  const cardNumberStr = String(cardNumber);
  const last4Digits = cardNumberStr.slice(-4);
  return last4Digits.padStart(cardNumberStr.length, '*');
}

We can now give it a try.

console.log(maskCreditCard(56199487)); // ****9487
console.log(maskCreditCard(4974587021678701)); // ************8701

To finish this lecture, the last simple method I want to show you is the repeat() method. This method allows to repeat a string multiple times. As an example, let's say there is some bad weather at one airport. When such a situation happens, they usually have those long messages on the screen that keeps on repeating all the time.

Let's consider the below example:

const badWeather = 'Bad weather, All departures are delayed. ';
const repeatedBadWeather = badWeather.repeat(3);
console.log(repeatedBadWeather); // Bad weather, All departures are delayed. Bad weather, All departures are delayed. Bad weather, All departures are delayed.

Great! We didn't talk about all the string methods that exist in JavaScript. But, if you want to check them out, you can do so on MDN.