0

So to practice javascript I'm making a little game and I ran into a problem that I have not idea how to solve.

I want to replace the character/letter in the word by a array or index number. For example "letter"

0: l
1: e
2: t
3: t
4: e
5: r

So in this case I want to change 3th character to character "b" making it to be "letber"

var newStr = myStr.replace(/_/t, "b"); This approach is not optional for me, it would ruin the purpose of my game.

I also took a look into .slice and .replace options but i couldn't figure out how to use it the way I explained.

trincot
  • 317,000
  • 35
  • 244
  • 286
MAT fg
  • 3
  • 1

2 Answers2

0

Substring replace character. substring(start,end) is inclusive on start and exclusive on end. So "hello".substring(1,3) will be 'el'.

var x = "letter"
var index = 3
x = x.substr(0, index) + 'x' + x.substr(index + 1);
console.log(x);

output: letxer

0

Actually you are trying to change a character from a string. Which is a primitive type. Since they are immutable values you can't directly change them like array items. You need to create a new string to get that working.

const word = 'letter';
const changedWord = word.substring(0, 3) + 'b' + word.substring(4);
console.log(changedWord)
Sifat Haque
  • 5,357
  • 1
  • 16
  • 23