/dedent

Removes code-formatting indentation from multiline template literals.

Primary LanguageJavaScriptMIT LicenseMIT

dedent

Removes code-formatting indentation from multiline template literals.

Description

Multiline template string literals are great! — Until they're not.

While it is nice not having to concatenate multiple strings ending in "\n" together in order to create multiline blocks of text, it is annoying that string literals drag along their excess code-indentation baggage wherever they go.

For example:

(function outputOverIndentedText() {
  const culprit = 'code indentation'

  console.log(`
    This block
      of text
        contains the
    ${culprit}.
  `)
}())

Outputs:

    This block
      of text
        contains the
    code indentation.

Note the wide margin created from the indentation of the code-formatting being embedded into the string literal.

A "dedent" function — such as this one — solves this by removing the indentation caused by code-formatting, and returns a block of text with what is assumed to be the intended level of indentation.

The idea is to determine which line has the smallest indent and to remove that indent from all lines. Additionally, leading and trailing whitespace is trimmed.

Usage

dedent can be called as a tag function:

import textBlock from './dedent.js'

(function outputCorrectlyIndentedText() {
  const culprit = 'code indentation'

  console.log(textBlock`
    This block
      of text
        does not contain the
    ${culprit}.
  `)
}())

Output:

This block
  of text
    does not contain the
code indentation.

Or dedent can be called as a "standard" function:

import textBlock from './dedent.js'

(function outputDedentedHtml() {
  console.log(textBlock(`
    <pre>
      Why am I logging HTML
        to the console?
    </pre>
  `))

  const url = 'https://example.com/'
  const hyperlink = `
    <a href="${url}">
      Click Me.
    </a>
  `
  console.log(textBlock(hyperlink))
}())

Output:

<pre>
  Why am I logging HTML
    to the console?
</pre>
<a href="https://example.com/">
  Click Me.
</a>

Discussions