String replace multiple characters with an asterisk in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a string as the first argument and an array of numbers. Our function should replace all the characters in the string at indices that are specified by the array elements taken as the second argument with an asterisk.

Example

The code for this will be −

const str = "Lorem ipsum dolor sit amet consectetur adipiscing elit";
const arr = [4, 7, 9, 12, 15];
const replceWithAsterisk = (str, indices) => {
   let res = '';
   res = indices.reduce((acc, val) => {
      acc[val] = '*';
      return acc;
   }, str.split('')).join('');
   return res;
};
console.log(replceWithAsterisk(str, arr));

Output

The output in the console −

Lore* i*s*m *ol*r sit amet consectetur adipiscing elit
raja
Published on 12-Oct-2020 15:09:05
Advertisements