flowernal
flowernal

Reputation: 61

How can I replace MORE characters at a particular index in JS?

I know how to replace one character at a particular index, but I don't know, how can I replace more characters.

I already tried FOR loop, but it didn't work.

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], "?");
}

The str after loop should be "h?ll? wor?d", but it's "hello world"

Upvotes: 0

Views: 73

Answers (2)

Ganhammar
Ganhammar

Reputation: 1951

If you look at your replaceAt method your not changing the passed string (which wouldn't be possible since strings is immutable), your creating a new one, so if you change your for loop to replace the string it will work:

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], "?");
}

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386512

You need an assignment for every step of replacement.

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

Upvotes: 2

Related Questions