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");
The first method is by using the substr() method. And in the second method, we will convert the string to an array and replace the character at the index. Both methods are described below: Using the substr() method: The substr() method is used to extract a sub-string from a given starting index to another index.
Unlike String Class, the StringBuilder class is used to represent a mutable string of characters and has a predefined method for change a character at a specific index – setCharAt(). Replace the character at the specific index by calling this method and passing the character and the index as the parameter.
Using 'str.replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
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.substr(0, index) + replacement + this.substr(index + replacement.length); }
And use it like this:
var hello = "Hello World"; alert(hello.replaceAt(2, "!!")); // He!!o World
There is no replaceAt
function in JavaScript. You can use the following code to replace any character in any string at specified position:
function rep() { var str = 'Hello World'; str = setCharAt(str,4,'a'); alert(str); } function setCharAt(str,index,chr) { if(index > str.length-1) return str; return str.substring(0,index) + chr + str.substring(index+1); }
<button onclick="rep();">click</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With