Replace all characters in a string except the ones that exist in an array JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, we have to write a function −

replaceChar(str, arr, [char])

Now, replace all characters of string str that are not present in array of strings arr with the optional argument char. If char is not provided, replace them with ‘*’.

Let’s write the code for this function.

The full code will be −


const arr = ['a', 'e', 'i', 'o', 'u'];
const text = 'I looked for Mary and Samantha at the bus station.';
const replaceChar = (str, arr, char = '*') => {
   const replacedString = str.split("").map(word => {
      return arr.includes(word) ? word : char;
   return replacedString;
console.log(replaceChar(text, arr));


The console output of this code will be −

Published on 19-Aug-2020 10:46:05