Replacing parts of a string - replace and replaceAll

In JavaScript, you can replace parts of a string using the replace() method. This method takes two parameters:

  1. the part of the string you want to replace
  2. the new string you want to replace it with

For example, let's say we have a string called name:

Loading Code . . .

We can replace the letter i with the letter o using the replace() method:

Loading Code . . .

The replace() method only replaces the first instance of the string you want to replace. So, if we have a string with multiple instances of the string we want to replace, only the first instance will be replaced:

Loading Code . . .

Note that the replace() method did not replace the second instance of the string we wanted to replace.

Also note that the replace() method is case-sensitive and it does not modify the original string. Instead, it returns a new string with the replaced part.

Replacing all instances of a string

The replace() method only replaces the first instance of the string you want to replace. If you want to replace all instances of a string, you can use the replaceAll() method. This method takes two parameters:

  1. the part of the string you want to replace
  2. the new string you want to replace it with
Loading Code . . .

There are more advanced ways to replace parts of a string, but we will not cover them now. We'll cover them in a later lesson, when we learn about Regular Expressions.

Code Challenge

You are working on a secret messaging app and you need to implement a function that can convert a message into a secret message by replacing certain characters with other characters.

Write a function called convertToSecretMessage that takes a string as an argument and returns a new string where the characters 'a', 'e', 'i', 'o', and 'u' are replaced with '1', '2', '3', '4', and '5', respectively.

For example, calling convertToSecretMessage('hello world') should return the string "h2ll4 w4rld".

Remember that it needs to work for both uppercase and lowercase letters.

Loading...
Loading...
Loading...

© 2024 - ®Mewters