 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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**
Advertisements
 