函数接受3个输入:(字符串(str),字符串的起始点(index),以及在此之后要删除多少字符(count))
function removeFromString(str, index, count) {
let newStr = '';
for (let i = index; i <= (index + count); i++) {
newStr = str.replace(str[i], '');
}
return newStr;
}
它返回的输出可能最多删除一个字符,但仅此而已,这不是我想要实现的。
我想要的是一个函数,当调用时,将返回一个不包含index和count参数指定的字符的函数。
With
newStr = str.replace(str[i], '')
您总是将str
作为要替换的基字符串-这是原始输入。你永远不会使用newStr
,除非在最后一次迭代之后;在此之前更换的产品将会丢失。
另一个问题是,str.replace(str[i], '')
将替换相同的字符,如果它存在于字符串的较早位置,而不是在您想要的索引位置。
将字符串的索引切片。
const removeFromString = (str, index, count) => (
str.slice(0, index + 1) + str.slice(index + count + 1)
);
console.log(removeFromString('123456', 2, 2));
只是使用JS的子字符串方法的问题。
来自Mozilla Developer Network的子字符串方法定义
function removeFromString(str, index, count) {
return str.substring(0, index) + str.substring(index+count);
}
console.log(removeFromString('fofonka', 2, 2));