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


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 −

Example

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;
   }).join("");
   return replacedString;
};
console.log(replaceChar(text, arr));

Output

The console output of this code will be −

***oo*e***o***a***a****a*a***a*a****e**u****a*io**

Updated on: 19-Aug-2020

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements