清除多行字符串中的缩进

这篇博客介绍了如何使用dedent包来清理JavaScript中多行字符串的前导和尾随空格,使代码更美观。dedent不仅可以去除缩进,还能修剪首尾空白行,方便编写和阅读代码,例如在创建Markdown列表或多行字符串时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在制作脚手架过程中,会经常给出多行字符串提示,但是这些字符串默认会有很多缩进,影响美观。所以通过此包进行清除。

npm i @michaelray/dedent -D

 使用方法

 import dedent from "dedent";

function usageExample() {
  const first = dedent`A string that gets so long you need to break it over
                       multiple lines. Luckily dedent is here to keep it
                       readable without lots of spaces ending up in the string
                       itself.`;

  const second = dedent`
    Leading and trailing lines will be trimmed, so you can write something like
    this and have it work as you expect:

      * how convenient it is
      * that I can use an indented list
         - and still have it do the right thing

    That's all.
  `;

  const third = dedent(`
    Wait! I lied. Dedent can also be used as a function.
  `);

  return first + "\n\n" + second + "\n\n" + third;
}
console.log(usageExample());
A string that gets so long you need to break it over
multiple lines. Luckily dedent is here to keep it
readable without lots of spaces ending up in the string
itself.

Leading and trailing lines will be trimmed, so you can write something like
this and have it work as you expect:

  * how convenient it is
  * that I can use an indented list
    - and still have it do the right thing

That's all.

Wait! I lied. Dedent can also be used as a function.

https://www.npmjs.com/package/@michaelray/dedent 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值