![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
String replace multiple characters with an asterisk in JavaScript
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
Advertisements