
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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 Specific Ones in 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