字串替換功能以取代字串 JavaScript 中字元的第 n 次出現
我們需要編寫一個叫 removeStr() 的函式,該函式存於 String.prototype 物件中,而且需要字串 str、字元 char 和數字 n。
該函式應從 str 中移除 char 的第 n 次出現。
讓我們編寫此程式碼−
const str = 'aaaaaa';
const subStr = 'a';
const num = 6;
removeStr = function(subStr, num){
if(!this.includes(subStr)){
return -1;
}
let start = 0, end = subStr.length;
let occurences = 0;
for(; ;end < this.length){
if(this.substring(start, end) === subStr){
occurences++;
};
if(occurences === num){
return this.substring(0, start) + this.substring(end, this.length);
};
end++;
start++;
}
return -1;
}
String.prototype.removeStr = removeStr;
console.log(str.removeStr(subStr, num));控制檯中此程式碼的輸出將為 −
aaaaa
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP