替换掉 JavaScript 字符串中除数组中存在的字符以外的所有字符
假设我们必须编写一个函数 -
replaceChar(str, arr, [char])
现在,将字符串 str 中不存在于字符串数组 arr 中的所有字符替换为可选参数 char。如果未提供 char,则用 "*" 替换。使用以下格式调用函数。
让我们为这个函数编写代码。
完整的代码如下:
示例
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));输出
此代码的控制台输出将如下所示 -
***oo*e***o***a***a****a*a***a*a****e**u****a*io**
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP