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

var str = "hello world";

我需要这样的东西

str.replaceAt(0,"h");

当前回答

你不能。取位置前后的字符并连接成一个新字符串:

var s = "Hello world";
var index = 3;
s = s.substring(0, index) + 'x' + s.substring(index + 1);

其他回答

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

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

在Javascript中,字符串是不可变的,所以你必须这样做

var x = "Hello world"
x = x.substring(0, i) + 'h' + x.substring(i+1);

用'h'替换x在i处的字符

在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

可以使用以下函数替换字符串特定位置的字符或字符串。使用String.prototype.replaceAllMatches()函数替换以下所有匹配案例。

String.prototype.replaceMatch = function(matchkey, replaceStr, matchIndex) {
    var retStr = this, repeatedIndex = 0;
    for (var x = 0; (matchkey != null) && (retStr.indexOf(matchkey) > -1); x++) {
        if (repeatedIndex == 0 && x == 0) {
            repeatedIndex = retStr.indexOf(matchkey);
        } else { // matchIndex > 0
            repeatedIndex = retStr.indexOf(matchkey, repeatedIndex + 1);
        }
        if (x == matchIndex) {
            retStr = retStr.substring(0, repeatedIndex) + replaceStr + retStr.substring(repeatedIndex + (matchkey.length));
            matchkey = null; // To break the loop.
        }
    }
    return retStr;
};

测试:

var str = "yash yas $dfdas.**";

console.log('Index Matched replace : ', str.replaceMatch('as', '*', 2) );
console.log('Index Matched replace : ', str.replaceMatch('y', '~', 1) );

输出:

Index Matched replace :  yash yas $dfd*.**
Index Matched replace :  yash ~as $dfdas.**
str = str.split('');
str[3] = 'h';
str = str.join('');