用不同字元替換字串中指定下標的字元 - JavaScript
我們需要寫一個 JavaScript 函式,該函式將第一個引數作為字串,第二個引數作為數字(n),第三個引數作為字元(c)。這個函式應將字元的第 n 次出現用作第三個引數提供的字元替換,並返回新字串。
示例
以下是程式碼 −
const str = 'This is a sample string';
const num = 2;
const char = '*';
const replaceNthAppearance = (str, num, char) => {
const creds = str.split('').reduce((acc, val, ind, arr) => {
let { res, map } = acc;
if(!map.has(val)){
map.set(val, 1);
if(num === 0){
res += char;
}else{
res += val;
}
}else{
const freq = map.get(val);
if(num - freq === 1){
res += char;
}else{
res += val;
};
map.set(val, freq+1);
};
return { res, map };
}, {
res: '',
map: new Map()
});
return creds.res;
}
console.log(replaceNthAppearance(str, num, char));輸出
以下是控制檯的輸出 −
This ***a s*mple string
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
JavaScript
PHP