我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?

var str = "hello world";

我需要这样的东西

str.replaceAt(0,"h");

当前回答

使用扩展语法,你可以将字符串转换为数组,在给定位置分配字符,然后转换回字符串:

Const STR = "hello world"; 函数replace (s, i, c) { Const arr =[…s];//将字符串转换为数组 Arr [i] = c;//在pos i处设置字符c 返回arr.join(”);//返回字符串 } //打印"hallo world" console.log(replace (str, 1, 'a'));

其他回答

str = str.split('');
str[3] = 'h';
str = str.join('');

解决方案不工作的负索引,所以我添加了一个补丁。

String.prototype.replaceAt=function(index, character) {
    if(index>-1) return this.substr(0, index) + character + this.substr(index+character.length);
    else return this.substr(0, this.length+index) + character + this.substr(index+character.length);
    
}

假设你想用“Z”替换第k个索引(基于0的索引)。 你可以用正则表达式来做这个。

var re = var re = new RegExp("((.){" + K + "})((.){1})")
str.replace(re, "$1A$`");

在JavaScript中,字符串是不可变的,这意味着您所能做的最好的事情就是用更改后的内容创建一个新的字符串,并将变量赋值指向它。

你需要自己定义replace()函数:

String.prototype.replaceAt = function(index, replacement) {
    return this.substring(0, index) + replacement + this.substring(index + replacement.length);
}

像这样使用它:

var hello = "Hello World";
alert(hello.replaceAt(2, "!!")); // He!!o World

使用扩展语法,你可以将字符串转换为数组,在给定位置分配字符,然后转换回字符串:

Const STR = "hello world"; 函数replace (s, i, c) { Const arr =[…s];//将字符串转换为数组 Arr [i] = c;//在pos i处设置字符c 返回arr.join(”);//返回字符串 } //打印"hallo world" console.log(replace (str, 1, 'a'));