iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐙

Introduction to dedent: Easily Handling Multi-line Strings in JavaScript

に公開

Libraries

Situation

  • I want to handle line breaks using trim() and backticks, etc.
const text = `
In this state,
line breaks are realized cleanly
`.trim();
In this state,
line breaks are realized cleanly
	const text = `
	If there is indentation,
	it will include the indentation.
	`.trim();
	If there is indentation,
	it will include the indentation.

Solutions

JS

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

npm install dedent

TS

https://www.npmjs.com/package/ts-dedent

npm install ts-dedent

Use this for TS.

Actual Code

import dedent from "ts-dedent";

Since I am in a TS environment, I installed ts-dedent.

	const text = dedent`
	Even with indentation,
	it's now without indentation!
	`.trim();
Even with indentation,
it's now without indentation!

Example

 const canvasTexture = new THREE.CanvasTexture(
+     this.createCanvasForTexture(w * 20, h * 20, String(dedent(text)), f)
 );

Since calling it for every piece of text was a hassle, I integrated dedent into my custom text rendering class to format everything at once. It's very easy to use and super handy!

Reference Pages

https://qiita.com/Ryo-Nakano/items/1689f2bdca999a96dc74#20230125--stringdedent-なるものが使えるようになるかも
https://www.webdelog.info/entry/2021/06/20/184841

Discussion