js replace the character at the specified position in the string

Posted May 27, 20201 min read

Suppose there is a string, maybe 'Good Morning' may be' Hello World', I want to replace the fifth character with '-'.
Because the string can get the character 'Hello World' [4] at a certain position like an array, but cannot directly modify the character 'Hello World' [4]= '-' like an array, so It doesn't work, but you can split it into arrays, modify the value at a certain position, and then merge them back.
method 1:

const replaceStr1 =(str, index, char) => {
    const strAry = str.split('');
    strAry [index]= char;
    return strAry.join('');
  replaceStr(str1, 4, '-'); //=> Good-Morning
  replaceStr(str2, 4, '-'); //=> Hell- World

The js string has a substring method, which is used to extract the characters between two specified subscripts in the string, which means that you can use'Hello World'.substring(0, 4)to getHell, Add the character to be replaced, and then add the following character string.
Method 2:

const replaceStr2 =(str, index, char) => {
    return str.substring(0, index) + char + str.substring(index + 1);
  replaceStr2(str1, 4, '-'); //=> Good-Morning
  replaceStr2(str2, 4, '-'); //=> Hell- World

If there is an easier way, please leave a message ~