I have a string, let's say Hello world
and I need to replace the char at index 3. How can I replace a char by specifying a index?
var str = "hello world";
I need something like
str.replaceAt(0,"h");
I have a string, let's say Hello world
and I need to replace the char at index 3. How can I replace a char by specifying a index?
var str = "hello world";
I need something like
str.replaceAt(0,"h");
In Javascript strings are immutable so you have to do something like
To replace the character in x at i with 'h'
You can extend the string type to include the inset method:
Then you can call the function:
@CemKalyoncu: Thanks for the great answer!
I also adapted it slightly to make it more like the Array.splice method (and took @Ates' note into consideration):
There are lot of answers here, and all of them are based on two methods:
Personally, I would use these two methods in different cases. Let me explain.
@FabioPhms: Your method was the one I initially used and I was afraid that it is bad on string with lots of characters. However, question is what's a lot of characters? I tested it on 10 "lorem ipsum" paragraphs and it took a few milliseconds. Then I tested it on 10 times larger string - there was really no big difference. Hm.
@vsync, @Cory Mawhorter: Your comments are unambiguous; however, again, what is a large string? I agree that for 32...100kb performance should better and one should use substring-variant for this one operation of character replacement.
But what will happen if I have to make quite a few replacements?
I needed to perform my own tests to prove what is faster in that case. Let's say we have an algorithm that will manipulate a relatively short string that consists of 1000 characters. We expect that in average each character in that string will be replaced ~100 times. So, the code to test something like this is:
I created a fiddle for this, and it's here. There are two tests, TEST1 (substring) and TEST2 (array conversion).
Results:
It seems that array conversion beats substring by 2 orders of magnitude! So - what the hell happened here???
What actually happens is that all operations in TEST2 are done on array itself, using assignment expression like
strarr2[p] = n
. Assignment is really fast compared to substring on a large string, and its clear that it's going to win.So, it's all about choosing the right tool for the job. Again.
In JavaScript, strings are immutable, which means the best you can do is 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:And use it like this:
The methods on here are complicated. I would do it this way:
This is as simple as it gets.