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

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

任何想法吗?


当前回答

最短的方法是使用拼接

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

其他回答

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

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

你可以这样使用:if (str[4] === 'r') str = str.slice(0,4) + str.slice(5)

解释:

If (str[4] === 'r') 检查第5个字符是否为“r” str.slice (0, 4) 对字符串进行切片,以获得'r'之前的所有内容 + str.slice (5) 添加字符串的其余部分。

缩小:s = s[4] = =‘r’吗? s.slice (0, 4) + s.slice (5): s[37个字节!] 演示:

function remove5thR (s) s = s[4] =‘r’? s。切片(0.4)+ s。切片(5):s; 控制台日志(s);//输出日志 的 移除5thr ('crt/r2002_2') // > 'crt/2002_2' remove5thR(“crt | r2002_2 ') // > ' crt | 2002_2” 删除5thr(“rrrrr”)// >“rrrr” 删除5thr(“RRRRR”)// >“RRRRR”(不改变)

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

这是因为当char等于""时,char。Length是0,所以子字符串组合成原始字符串。按照您的代码尝试,以下将工作:

String.prototype.replaceAt = function (index, char) {
    return this.substr(0, index) + char + this.substr(index + 1);
    //   this will 'replace' the character at index with char ^
}

演示

在c# (Sharp)中,你可以创建一个空字符'\0'。 也许你可以这样做:

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

在谷歌上搜索或在互联网上冲浪,检查javascript是否允许您制作空字符,就像c#一样。如果是,那么学习如何做到这一点,也许replacat函数最终会工作,并且您将实现您想要的!

最后,'r'字符将被删除!

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

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