[Javascript] How can I replace a character at a given index of a string?


I want to replace a character present at a given index of a string. How can I do that in Javascript?

1 Answer

3 years ago by

Javascript doesn't have a inbuilt function to replace a character at a given index of a string. You can use substring() to achieve this functionality as shown below.

let str = 'This is s test message';

let replacementStr = (index, replaceChar) => str.substring(0, index) + replaceChar + str.substring(index + replaceChar.length);
console.log(replacementStr(8, 'a ')); //Outputs 'This is a test message'

Run here https://onecompiler.com/javascript/3xnrxxqd8

3 years ago by Meera