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

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

任何想法吗?


当前回答

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

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));

其他回答

最短的方法是使用拼接

var inputString = "abc";
// convert to array and remove 1 element at position 4 and save directly to the array itself
let result = inputString.split("").splice(3, 1).join();
console.log(result);

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

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

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

使用[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

对于'/r'的全局替换,这段代码适合我。

mystring = mystring.replace(/\/r/g,'');

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