var str = "Hello world";
str.charAt(2)="P"//instead of l i am assigning the value P
console.log(str)
Asked
Active
Viewed 227 times
0

sarangkkl
- 773
- 3
- 15
2 Answers
1
You need to make an array out of the string to replace by index. The following should do the trick.
const changeChar = (str, newValue, index) => {
let splitted = str.split("");
splitted[index] = newValue;
return splitted.join("");
}

Palladium02
- 1,134
- 1
- 4
- 13
1
In JavaScript, strings are immutable, there are 2 ways you can do this which I have mentioned below
1 way can be to split the string using two substrings and stuff the character between them
var s = "Hello world";
var index = 2;
s = s.substring(0, index) + 'p' + s.substring(index + 1);
console.log(s)
2 way can be to convert the string to character array, replace one array member and join it
var str="Hello World"
str = str.split('');
str[2] = 'p';
str = str.join('');
console.log(str)

Ahmed Ali
- 257
- 1
- 7