
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Replace multiple instances of text surrounded by specific characters in JavaScript?
- Replace all characters in a string except the ones that exist in an array JavaScript
- Replace characters in a string in Arduino
- How to replace characters on String in Java?
- How to Replace characters in a Golang string?
- Longest string with two distinct characters in JavaScript
- How to replace characters except last with a mask character in JavaScript?
- JavaScript regex - How to replace special characters?
- Remove characters from a string contained in another string with JavaScript?
- Match multiple occurrences in a string with JavaScript?
- Mapping unique characters of string to an array - JavaScript
- Generate random string/characters in JavaScript?
- Replace String with another in java.
- Replace words of a string - JavaScript
- Assigning multiple characters in an int in C language

Advertisements