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

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

任何想法吗?


当前回答

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

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

其他回答

所以基本上,另一种方法是:

使用array .from()方法将字符串转换为数组。 遍历数组并删除除索引为1的字母外的所有r字母。 将数组转换回字符串。

let arr = Array.from("crt/r2002_2"); 加勒比海盗。forEach((信,i) = >{如果(信= = =‘r’& &我! = = 1)arr[我 ] = "" }); document . write (arr.join (" "));

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

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

我不喜欢使用replace函数从字符串中删除字符。那样做是不合逻辑的。通常我用c# (Sharp)编程,每当我想从字符串中删除字符时,我使用string类的remove方法,但没有Replace方法,即使它存在,因为当我要删除时,我只删除,不替换。这是合乎逻辑的!

在Javascript中,字符串没有remove函数,但是有substr函数。可以使用substr函数一次或两次从字符串中删除字符。您可以使用下面的函数删除字符串末尾的起始索引处的字符,就像c#方法首先重载string一样。删除(int startIndex):

function Remove(str, startIndex) {
    return str.substr(0, startIndex);
}

和/或你也可以让下面的函数删除字符在开始索引和计数,就像c#方法第二次重载字符串。删除(int startIndex, int count):

function Remove(str, startIndex, count) {
    return str.substr(0, startIndex) + str.substr(startIndex + count);
}

然后您可以使用这两个函数或其中一个来满足您的需要!

例子:

alert(Remove("crt/r2002_2", 4, 1));

输出:crt / 2002 _2

如果您在大型项目中经常这样做,那么通过使用没有逻辑的技术来实现目标可能会导致对代码的理解混乱,并在未来出现错误!

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

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

char。长度为零。在这种情况下,您需要添加1以跳过字符。