Javascript: Replace a character in string at given index

While working with javascript, there is often a requirement to replace a character at a particular index. This article will discuss how to replace at a specific index in a javascript string using different methods and example illustrations.
Javascript does not have an in-built method to replace a particular index. Therefore, one has to create a custom function to fulfill the purpose. Since strings are immutable in javascript, one needs to create a new string with the modified value and then assign this value to the string variable we need to change.

Javascript: String replace at index using substring()

The substring() method in javascript returns a string segment between start and end indexes or to the end of the string.

Example:-

Replace the character at index position at 5th place with * in the string “Helloo Javascript”

Function:-

String.prototype.replaceAtIndex = function(_index, _newValue) {
    return this.substr(0, _index) + _newValue + this.substr(_index + _newValue.length)
}

Usage:-

let string1 = "Helloo Javascript"
final_string = string1.replaceAtIndex(5,"*")
console.log(final_string)

Output:-

Hello* Javascript

Another way to write and use the function for replacing character a particular index is:

Function:-

function replaceAtIndex(_string,_index,_newValue) {
    if(_index > _string.length-1) 
    {
        return string
    }
    else{
    return _string.substring(0,_index) + _newValue + _string.substring(_index+1)
    }
}

Usage:-

let final_string = replaceAtIndex("Helloo Javascript", 5, "*" )
console.log(final_string)

Output:-

Hello* Javascript

Javascript: String replace at index using split() and join()

The split() method in javascript divides strings into substrings, and these substrings are then put into an array. Finally, the array is returned. The first parameter passed in the split() method is used to search within the string on which the method is applied and divide the string accordingly.

The join() method in javascript joins the elements of array into a string.

Example:-

Replace the character at index position at 5th place with * in the string “Helloo Javascript”

Function:-

function replaceAtIndex(_string,_index,_newValue) {
    split_string = _string.substring(0, _index) + ' ' + _string.substring(_index + 1);
    return_string = split_string.split('');
    return_string[_index] = '*';
    return_string = return_string.join('');
    return return_string;
}

Usage:-

let final_string = replaceAtIndex("Helloo Javascript",5,"*")
console.log(final_string)

Output:-

Hello* Javascript

Read More:

We hope this article helped you to replace a particular index in a javascript string. Good Luck !!!

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top