我就快拿到了,但就是不太对。 我想做的就是从字符串中删除字符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);
}

其他回答

这是对简单答案的改进(省略长度)

s.slice(0, 4) + s.slice(5)

Let s = "crt/r2002_2"; 设o = s.slice(0,4) + s.slice(5); let delAtIdx = (s, i) => s.slice(0, i) + s.slice(i + 1);//删除索引I处的字母 console.log (o); console.log (delAtIdx (s, 4));

如果它总是在你的字符串中的第4个字符,你可以尝试:

yourString.replace(/^(.{4})(r)/, function($1, $2) { return $2; });

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

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

也许我是个新手,但我今天遇到了这些,它们看起来都不必要地复杂。

这里有一个更简单的方法(对我来说)从字符串中删除任何你想要的东西。

function removeForbiddenCharacters(input) {
let forbiddenChars = ['/', '?', '&','=','.','"']

for (let char of forbiddenChars){
    input = input.split(char).join('');
}
return input

}

只需修复您的替换:

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

mystring.replaceAt(4, 1);

我把它命名为removeAt。:)