字符串函数替换字符串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
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短