September 23, 2023

Replacing a character from string by index using javascript?

while Development, you might face how to replace character from a given string at a particular index.

Here are the top three ways to replace a character from string using a given index. The string doesn’t have a direct method to replace a character at a particular index, like in array we have splice method. So we need to take help of other string methods to achieve this functionality

  • using substring method
  • using replace method
  • using character array

Using substring method

As we know the substring method helps to get part of the string by using the startIndex and endIndex.

Let’s create functionality for replacing a character from string by given index

const word = 'Hello World';
function replaceUsingIndex(data,index,replaceMent){
    if(index >= data.length) return data;
  
    return data.substring(0,index)+replaceMent+data.substring(index+1)
}
const result = replaceUsingIndex(word,5,'_');
console.log(result); //Hello_World

As you can see, In the above example we have created replaceUsingIndex function which takes three params, a given string, index, and replaceMent

we have divided string into two parts first part contains string up to the given index. It does not include endIndex character

and then we have added replacement character

In the second part of the string, we have taken a string from index+1 because we don’t need a character to be replaced in the string.

Using replace method

The replace method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced,

replace also takes the second parameter as a function where we can specify how the return text should be

for eg.

function replaceUsingIndex(data,index,replaceMent){
    var output  = data.replace(/./g,function(char,i){
          if(i === index){
            return replaceMent
          } 
      return char
    })
    return output;
}
var result1 = replaceUsingIndex(word,5,'_');
console.log(result1);

In the above example, /./g regex expression used which iterate through every character of the string, we have callback where we get every individual character and index, we are checking the index with our passed index to the function. If matches we are returning replacement character.

Using character array

const word = 'Hello World';
function replaceUsingIndex(data,index,replaceMent){
    var output  = data.split(''); //here [...data] also can work - valid for es6 support browser 
        output[index] = replaceMent;
    return output.join('');
}
var result2 = replaceUsingIndex(word,5,'_')
console.log(result2);

In the above example, using the split method we converted the string into a character array and replaced it at a particular index, and after re-assigning replacement character we are making back to the string using join method of Array

This method will perform slow for large string