Tengo la siguiente función JS que debería cambiar la palabra "hola" a "yo" al hacer clic en un botón si el usuario ha ingresado esto. Por ejemplo, "hola, ¿cómo estás hoy?" ==> "Oye, ¿cómo estás hoy?"
function changeWord() { let str = document.getElementById('inputBox').innerHTML; document.getElementById('inputBox').innerHTML = str.replace("hi", "yo");; }Lo anterior no funciona cuando llamo a changeWord(); al hacer clic, alguna idea?
Debería apuntar al valor de la entrada en lugar del HTML.
const input = document.querySelector('input'); const button = document.querySelector('button'); button.addEventListener('click', changeWord, false); function changeWord() { const str = input.value; input.value = str.replace("hi", "yo"); } <input type="text" /> <button>Click</button>Use .value en lugar de .innerHTML, así:
let str = document.getElementById('inputBox').value; document.getElementById('inputBox').value = str.replace("hi", "yo");