如何删除模板文字中的多余空格?

dra*_*m95 6 javascript string function

当我创建模板文字时,我会使用trim() 来删除多余的空间。但我注意到,当我在 JS 函数中执行此操作时,它仍然会创建额外的制表符或空白。

  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();
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

您可以看到第一行如何正常显示,但第二行具有所有必要的选项卡。

Jua*_*des 8

一种解决方案是将字符串分成几行,然后修剪每一行。

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)
Run Code Online (Sandbox Code Playgroud)

如果是我,在这种情况下,我会把文字塞到左边,看起来仍然足够可读。

          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.`;
Run Code Online (Sandbox Code Playgroud)