如何在模板文字中去除额外的空格?

4

创建模板文字时,我通常使用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.

您可以看到第一行显示正常,但第二行具有所有必要的制表符。


1
实际上,它们应该从第一个开始而不是缩进。唯一的解决方法是在输出时替换所有制表符。.replace(/\t/g, ''); - epascarello
1
取消单词“Take”及其后面的所有缩进。您已经创建了一个带有大量空格的多行字符串,并且trim()仅适用于字符串的前导和尾随空格。 - Andy Ray
https://dev59.com/dFoU5IYBdhLWcg3wk3l2 - epascarello
6个回答

5
一种解决方法是将字符串拆分为多行,并对每一行进行修剪。

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)

如果是我,在这种情况下,我会将文本靠左对齐,这样它看起来仍然足够可读。

          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.`;

2
你可以使用全局替换来去除双空格和制表符,将其转换为单个空格,非常简单,例如:
```javascript str.replace(/[\t\s]+/g, ' '); ```
其中,`str`是需要处理的字符串。
let result = myStrToReplace.replaceAll("\t", "").replaceAll("  ", " ").trim();

2

将任何长度为2的空格序列或\t或\n符号替换为' '或''。

const lineOne = `
                    ${1} bottles of beer on the wall, ${2} bottles of beer.
                    Take one down pass it around, ${1} bottles of beer on the wall.
                    `
    
  console.log(lineOne.replace(/(\s\s+|[\t\n])/g, ' ').trim())


1

这是因为行缩进在模板字面量引号内部。为了避免这种情况,将语句分成多个模板字面量,并使用与第一个文本块相同的方式将它们连接起来,使用\n字符表示新行。例如:

var lineOne = `My first line.\n`
+ `My second line.`.trim();
console.log(lineOne);      

输出:

My first line.
My second line.

1

将语句分为多个模板字面量,并以与第一个文本块中相同的方式将它们连接起来,使用 \n 字符表示新行。


0
一种解决方案是通过npm安装theredoc
另一种方法是将这两行代码复制粘贴到您的项目中:
let trimDoc=(d)=>d.replace(new RegExp(`^.{0,${d.match(/(?<=^|\n)( *).*$/)?.[1]?.length??0}}`,'mg'),'');
let eof:B=(a,...b)=>trimDoc(a.reduce((c,x,i)=>c+x+(b[i]??''),'').replace(/^.*\n/,''));

使用方法:

const document = eof`
    my document
        indented
    iscool`;

输出与以下内容相同:

const document = "my document\n    indented\niscool"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接