0

I am trying to change the string displayed in the frontend by using a function in javascript.

let displayword = document.getElementById("displayword”)
    console.log(displayword.innerText)     //apple

Say, I want the change the letter “l” to something else say “i” but keep the rest of the letters unchanged how do I go around this?

Things I have tried

displayword.innerText[3] = “i”           // -----does nothing----

I am confused why the above code using index does nothing, while the below does something

dash.innerText += “i”      //applei

Extra question: Why does the above code using =+ change the formatting of the innerText? I want to keep the large font but it changes to regular font of the element (here I am using h1).

Thank you:)

  • 1
    The += operator is explained [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition_assignment). – Robert Harvey Dec 29 '21 at 15:03
  • 1
    Does this answer your question? [How do I replace a character at a particular index in JavaScript?](https://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript) – Robert Harvey Dec 29 '21 at 15:04
  • a string it not an array, its not like in other languages an array of chars, just look at https://www.w3schools.com/jsref/jsref_obj_string.asp – mech Dec 29 '21 at 15:08

2 Answers2

1

You should look at the String documentation, especially String.slice and String.substring

In many languages, Strings can't be modified directly. Instead you "change" it by creating a new string composed of parts of the original.

As for how you'd do it in your case:

var text = displayWord.innerText;
text = text.slice(0, 3) + 'i' + text.slice(4) // apple -> appie
displayWord.innerText = text;

[Edited code slightly]

N. Kern
  • 401
  • 2
  • 7
0
displayword.innerText = displayword.innerText.replace(oldCharacter, newCharacter);

To replace all occurrences:

displayword.innerText = displayword.innerText.replaceAll(oldCharacter, newCharacter);
Al.G.
  • 4,327
  • 6
  • 31
  • 56
Julius
  • 491
  • 2
  • 10