我就快拿到了,但就是不太对。 我想做的就是从字符串中删除字符r。 问题是,字符串中r的实例不止一个。 但是,它总是索引4的字符(因此是第5个字符)。

示例字符串:crt/r2002_2

我想要什么:crt/2002_2

这个替换函数去掉了r

mystring.replace(/r/g, '')

生产:ct / 2002 _2

我尝试了这个函数:

String.prototype.replaceAt = function (index, char) {
    return this.substr(0, index) + char + this.substr(index + char.length);
}
mystring.replaceAt(4, '')

只有当我用另一个字符替换它时,它才会工作。它不会简单地移除它。

任何想法吗?


当前回答

下面的函数最适合我的例子:

public static cut(value: string, cutStart: number, cutEnd: number): string {
    return value.substring(0, cutStart) + value.substring(cutEnd + 1, value.length);
}

其他回答

只需修复您的替换:

String.prototype.replaceAt = function(index, charcount) {
  return this.substr(0, index) + this.substr(index + charcount);
}

mystring.replaceAt(4, 1);

我把它命名为removeAt。:)

总是有字符串函数,如果你知道你总是要删除第四个字符

str.slice(0, 4) + str.slice(5, str.length)

使用[index]位置来删除特定的字符

String.prototype.remplaceAt = function (index, distance) {
  return this.slice(0, index) + this.slice(index + distance, this.length);
};

来源:https://stackoverflow.com/users/62576/ken-white

让STR = '1234567'; 令index = 3; STR = STR .substring(0,索引)+ STR .substring(索引+ 1); Console.log (str) // 123567 -索引“3”下的数字“4”被删除

这个问题有很多应用。调整@simpleigh解决方案,使其更易于复制/粘贴:

function removeAt( str1, idx) {
  return str1.substr(0, idx) + str1.substr(idx+1)
}
console.log(removeAt('abbcdef', 1))  // prints: abcdef