DEV Community

Chinwendu Agbaetuo
Chinwendu Agbaetuo

Posted on • Edited on

1 1 1 1 1

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)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more