เราจำเป็นต้องเขียนฟังก์ชัน removeStr() ที่อยู่บนวัตถุ String.prototype และรับสตริง str อักขระ char และตัวเลข n
ฟังก์ชันควรลบลักษณะที่ n ของถ่านออกจาก str
มาเขียนโค้ดสำหรับสิ่งนี้กัน −
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