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:)
CodePudding user response:
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]
CodePudding user response:
displayword.innerText = displayword.innerText.replace(oldCharacter, newCharacter);
/*
To replace all occurrence
displayword.innerText = displayword.innerText.replaceAll(oldCharacter, newCharacter);
*/