Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"); 
like image 209
Santhosh Avatar asked Sep 16 '09 05:09

Santhosh


People also ask

How do you replace a string in a specific index?

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.

How do you change the character in a specific index in Java?

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.

How do you replace a specific character in a string?

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.


2 Answers

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 
like image 101
Cem Kalyoncu Avatar answered Oct 16 '22 21:10

Cem Kalyoncu


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>
like image 32
rahul Avatar answered Oct 16 '22 22:10

rahul