0

var str = "Hello world";

str.charAt(2)="P"//instead of l i am assigning the value P

console.log(str)
I want to replace some Text from the string by checking some coditions but i am getting error i also tried replace function but that return nothing does no changes in the string
sarangkkl
  • 773
  • 3
  • 15

2 Answers2

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