DEV Community

Chinwendu Agbaetuo
Chinwendu Agbaetuo

Posted on • Edited on

Search and replace letters of a string in JavaScript

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("");


  return replacedString;
}

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

Result


> Drostic meosures mode fost 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)