HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How do I replace a character at a specific index in JavaScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
replaceindexhowcharacterspecificjavascript

Problem

I have a string, let's say Hello world, and I need to replace the char at index 3. How can I replaced a char by specifying an index?

var str = "hello world";


I need something like

str.replaceAt(0,"h");

Solution

In JavaScript, strings are immutable, which means the best you can do is to create a new string with the changed content and assign the variable to point to it.

You'll need to define the replaceAt() function yourself:

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


And use it like this:

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

Code Snippets

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

Context

Stack Overflow Q#1431094, score: 858

Revisions (0)

No revisions yet.