替換掉 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