Skip to content

dedent

移除字符串中的缩进

385 bytes
since v12.3.0

使用方法

移除给定字符串中每行的缩进。可选择性地提供自定义的 indent 参数来控制要移除的缩进量。如果不提供 indent,则移除的缩进量由给定字符串的第一个非空行决定。

import * as _ from 'radashi'
// 显式指定缩进
_.dedent('\n Hello\n World!\n\n', ' ')
// => ' Hello\n World!\n'
// 自动检测缩进
_.dedent('\n Hello\n World!\n\n')
// => 'Hello\nWorld!\n'

标签模板字符串

在标签模板字符串中使用 dedent 时,缩进总是自动推断。

// 实际示例:邮件模板
const emailTemplate = _.dedent`
Hello, ${userName}!
Thank you for your recent purchase. Your order details are below:
Order ID: ${orderId}
Product: ${productName}
Quantity: ${quantity}
If you have any questions, please contact our support team.
Best regards,
The Support Team
`
// => `Hello, JohnDoe!
//
// Thank you for your recent purchase. Your order details are below:
// Order ID: 12345
// Product: Widget
// Quantity: 2
//
// If you have any questions, please contact our support team.
//
// Best regards,
// The Support Team`

多行嵌入字符串

使用 dedent 嵌入字符串时,无需担心嵌入字符串的缩进问题。例如,如果有一个数组,其中每个项都需要单独一行,只需用 join('\n') 连接它们,dedent 会确保一切正常。

const items = ['one', 'two', 'three']
const list = _.dedent`
My List:
${items.join('\n')}
`
// => 'My List:\n one\n two\n three'

间距问题?

有一个常见的使用场景是使用 if 条件和 dedent 构建一个由多个“段落”(暂时这么称呼)组成的长字符串。如果你无法在两个段落之间显示空行,你并不孤单,本节就是为你准备的。

由于 dedent 会去除给定字符串的首尾空行,默认情况下你的去缩进字符串周围没有间距。你可能会尝试在每个段落的开头包含一个空行来实现所需的间距,如下例所示。

let story = dedent`
There once was a programmer
who had a lot of trouble.
`
if (isLateAtNight()) {
story += dedent`
He was so confused
that he couldn't even
tell what was going on.
`
}
story
// =>
// There once was a programmer
// who had a lot of trouble.
// He was so confused
// that he couldn't even
// tell what was going on.

“He was so confused”上方的空行本意是将该段落与前一个段落分开。但如你所见,它没有起作用。你添加的空行被附加到了前一段落的最后一行(“who had a lot of trouble”)而不是作为一个单独的行。

以下是解决此问题的3种可能方案。选择你最喜欢的:

  1. 在空行中添加 \n

    story += dedent`
    \n
    He was so confused
    that he couldn't even
    tell what was going on.
    `
  2. 单独附加换行符。

    story += '\n\n'
    story += dedent`
    He was so confused
    that he couldn't even
    tell what was going on.
    `
  3. 在每个段落的开头包含两个空行。(不建议使用此方案,因为其意图不够明确)

    story += dedent`
    He was so confused
    that he couldn't even
    tell what was going on.
    `