如何在JS中的特定索引处替换更多字符?

时间:2019-06-23 19:08:50

标签: javascript replace

我知道如何在特定索引处替换一个字符,但是我不知道如何替换更多字符。

我已经尝试过FOR循环,但是没有用。

notes

events后循环应为String.prototype.replaceAt=function(index, replacement) { return this.substr(0, index) + replacement+ this.substr(index + replacement.length); } var str = "hello world"; var indices = [1, 4, 9]; for(i = 0; i < indices.length; i++) { str.replaceAt(indices[i], "?"); } ,但它为str

2 个答案:

答案 0 :(得分:2)

如果您查看自己的replaceAt方法,则不更改传递的字符串(因为字符串是不可变的,这是不可能的),因此您将创建一个新的字符串,因此,如果更改for循环以替换字符串会起作用:

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

var str = "hello world";
var indices = [1, 4, 9];

for(i = 0; i < indices.length; i++) {
    str = str.replaceAt(indices[i], "?");
}

答案 1 :(得分:1)

替换的每个步骤都需要分配作业。

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

var str = "hello world";
var indices = [1, 4, 9];

for (var i = 0; i < indices.length; i++) {
    str = str.replaceAt(indices[i], "?");
}

console.log(str);

相关问题