Quiero que cuando presione cualquier tecla del teclado, la cadena que está almacenada en la variable "array" (como una matriz) se escriba en el elemento "p", pero el problema es que cuando pongo un espacio vacío en la "cadena" variable (por tecla de tabulador o tecla de espacio) no escribe esos espacios vacíos, por lo que la oración sería así: "Helloworld".
window.onload = () => { let log = document.getElementById("log"); } let string = " Hello world \n How are you ?"; let array = string.split(""); let i = 0; log.addEventListener("click", () => { document.addEventListener("keypress", type); }) function type() { log.innerText += array[i]; i++; if (array[i] === undefined) { document.removeEventListener("keypress", type); } } #log { height: 50vh; width: 450px; padding: 15px; position: absolute; left: 10px; color: rgb(0, 255, 0); font-size: 18px; background-color: rgba(0, 0, 0, 0.7); border-radius: 25px; } #log::after { content: ""; position: absolute; width: 7px; height: 20px; background-color: rgb(0, 255, 0); animation-name: green; animation-duration: 1s; animation-iteration-count: infinite; } @keyframes green { 0% {background-color: rgb(0, 255, 0);} 25% {background-color: transparent;} 50% {background-color: rgb(0, 255, 0);} 75% {background-color: transparent;} 100% {background-color: rgb(0, 255, 0);} } <p id="log"></p>En lugar de leer de element.innerText, almacene el "texto hasta ahora" en otra variable de cadena y establezca el texto interno en el valor de esa variable.
window.onload = () => { let log = document.getElementById("log"); } let string = " Hello world \n\tHow are you ?"; let array = string.split(""); let i = 0; let words = ""; log.addEventListener("click", () => { document.addEventListener("keypress", type); }) function type() { words += array[i]; log.innerText = words; i++; if (array[i] === undefined) { document.removeEventListener("keypress", type); } } #log { height: 50vh; width: 450px; padding: 15px; position: absolute; left: 10px; color: rgb(0, 255, 0); font-size: 18px; background-color: rgba(0, 0, 0, 0.7); border-radius: 25px; } #log::after { content: ""; position: absolute; width: 7px; height: 20px; background-color: rgb(0, 255, 0); animation-name: green; animation-duration: 1s; animation-iteration-count: infinite; } @keyframes green { 0% {background-color: rgb(0, 255, 0);} 25% {background-color: transparent;} 50% {background-color: rgb(0, 255, 0);} 75% {background-color: transparent;} 100% {background-color: rgb(0, 255, 0);} } <pre id="log"></pre>