A method that replaces characters in a particular index in JavaScript

Asked 2 years ago, Updated 2 years ago, 40 views

For example, if there is a word "Hello world", change the letter of index number 4 to blank

var str = "hello world"; This is...

str.replaceAt(4,""); I want to make it "hell world" in this way, but is there a method like replaceAt?

javascript string

2022-09-22 08:57

1 Answers

In JavaScript, the string is imutable, so it is impossible to modify a specific index. Alternatively, there is a way to create a new string with only a specific index changed. I think you can directly define a function called replaceAt().

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

Like this. str = str.replaceAt(3, "a");


2022-09-22 08:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.