创建模板文字时,我通常使用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();
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.
您可以看到第一行显示正常,但第二行具有所有必要的制表符。
.replace(/\t/g, '');
- epascarellotrim()
仅适用于字符串的前导和尾随空格。 - Andy Ray