Cuando creo literales de plantilla, usaría trim() para eliminar el espacio adicional. Pero noté que cuando hago esto dentro de una función JS, todavía crea pestañas adicionales o espacios en blanco.
function BottlesOfBeer() { for (i = 99; i>=1; i--) { if (i === 1) { var oneBottle = "1 bottle of beer on the wall, 1 bottle of beer.\n" + "Take one down and pass it around, no more bottles of beer on the wall.\n" + "No more bottles of beer on the wall, no more bottles of beer.\n" + "Go to the store and buy some more, 99 bottles of beer on the wall."; console.log(oneBottle); } else { var lineOne = ` ${i} bottles of beer on the wall, ${i} bottles of beer. Take one down pass it around, ${i - 1} bottles of beer on the wall. `.trim(); console.log(lineOne); } } } BottlesOfBeer(); 99 bottles of beer on the wall, 99 bottles of beer. Take one down pass it around, 98 bottles of beer on the wall. 98 bottles of beer on the wall, 98 bottles of beer.Puedes ver como la primera línea aparece normalmente, pero la segunda tiene todas las pestañas necesarias.
divida la declaración en múltiples literales de plantilla y conéctelos de la misma manera que lo hizo en el primer bloque de texto, usando el carácter \n para indicar una nueva línea
Una solución es dividir la cuerda en líneas y recortar cada una de ellas.
const i = 1; const lineOne = ` ${i} bottles of beer on the wall, ${i} bottles of beer. Take one down pass it around, ${i - 1} bottles of beer on the wall. `.split("\n") .map(s => s.trim()) // If you want to remove empty lines. .filter(Boolean) .join("\n"); console.log(lineOne)Si fuera yo, en este caso, simplemente atascaría el texto contra la izquierda, todavía parece lo suficientemente legible.
const lineOne = `${i} bottles of beer on the wall, ${i} bottles of beer. Take one down pass it around, ${i - 1} bottles of beer on the wall.`;Puede usar un reemplazo global para eliminar espacios dobles y tabulaciones y cambiarlo a espacios simples, algo realmente simple como:
let result = myStrToReplace.replaceAll("\t", "").replaceAll(" ", " ").trim();