簡體   English   中英

如何刪除模板文字中的額外空間?

[英]How to remove extra space in template literals?

當我創建模板文字時,我會使用 trim() 來刪除多余的空間。 但我注意到當我在 JS function 中執行此操作時,它仍然會創建額外的制表符或空白。

 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.

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

您可以使用全局替換來刪除雙空格和制表符並將其更改為單個空格,非常簡單,例如:

let result = myStrToReplace.replaceAll("\t", "").replaceAll("  ", " ").trim();

發生這種情況是因為行縮進位於模板文字刻度線內。 為避免這種情況,將語句分解為多個模板文字並將它們連接在一起,就像在第一個文本塊中所做的那樣,使用\n字符表示新行。 例如:

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

印刷:

My first line.
My second line.

一種解決方案是將字符串分成幾行,並修剪每一行。

 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)

用最小長度 2 或 \t 或 \n 符號替換任何空間序列,並用 ' ' 或 '' 替換。 你需要什么。

 var 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())

將語句分解為多個模板文字,並按照與第一個文本塊中相同的方式將它們連接在一起,使用 \n 字符表示新行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM