Search and replace letters of a string in JavaScript

Chinwendu Agbaetuo - Oct 7 - - Dev Community

Create a function that accepts three parameters:

  1. A string where you want to replace a letter.
  2. The letter you want to replace (the second argument).
  3. The letter you want to use as a replacement (the third argument).

This function should replace all occurrences of the second letter with the third letter in the given string.

Solution

// searchAndReplace.js

function searchAndReplace(text, firstLetter, secondLetter) {
  const replacedString = text
    .split("")
    .map((item) => (item === firstLetter ? secondLetter : item))
    .join("");

  console.log(replacedString);
  return replacedString;
}

searchAndReplace("Drastic measures made fast", "a", "o");
Enter fullscreen mode Exit fullscreen mode

Result


> Drostic meosures mode fost 
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player