當我創建模板文字時,我會使用 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.
您可以看到第一行如何正常顯示,但第二行具有所有必需的選項卡。
uj5u.com熱心網友回復:
您可以使用全域替換來洗掉雙空格和制表符并將其更改為單個空格,這非常簡單,例如:
let result = myStrToReplace.replaceAll("\t", "").replaceAll(" ", " ").trim();
uj5u.com熱心網友回復:
發生這種情況是因為行縮進在模板文字刻度線內。為避免這種情況,將陳述句分成多個模板文字并將它們連接在一起,就像在第一個文本塊中所做的那樣,使用\n字符表示新行。例如:
var lineOne = `My first line.\n`
`My second line.`.trim();
console.log(lineOne);
印刷:
My first line.
My second line.
uj5u.com熱心網友回復:
用最小長度 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())
uj5u.com熱心網友回復:
一種解決方案是將字串分解成線,然后修剪每條線。
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.`;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/377652.html
標籤:javascript 细绳 功能
上一篇:查找字串中存在的所有int的總和
