dedent
Remove indentation from a string
Usage
Remove indentation from every line of a given string. Optionally, provide your own indent
to control the amount of indentation to remove. If you don’t provide an indent
, the amount of indentation to remove is determined by the first non-empty line of the given string.
Tagged template strings
When using dedent
in a tagged template string, the indentation is always inferred.
Multi-line embedded strings
When embedding a string with dedent
, you don’t have to worry about the indentation of the embedded string. For example, if you have an array where each item needs its own line, just join it with join('\n')
and dedent
will make sure it all works out.
Spacing issues?
There’s a common use case of building up a long string of “paragraphs” (for lack of a better word) using if
conditions and dedent
. If you can’t get an empty line to appear between two paragraphs, you’re not alone and this section is for you.
Since dedent
strips the first and last empty line of a given string, your dedented string has no spacing around it by default. You might try to include an empty line at the start of each paragraph to achieve the desired spacing, like the following example.
The empty line above “He was so confused” was intended to separate the paragraph from the previous one. But as you can see, it didn’t work. The empty line you added was appended to the last line of the previous paragraph (“who had a lot of trouble”) instead of being a separate line.
Here are 3 possible solutions for this issue. Pick your favorite:
-
Add
\n
to your empty line. -
Append the line breaks separately.
-
Include two empty lines at the start of each paragraph. (An unadvised solution as its intention is not the most clear)