字符串函数替换字符串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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短