Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-line strings preserving readability

I know I can have multi-line strings in JS with backticks, however, it also picks up spaces as part of the string. This is expected behavior, but I'd like them to be indented for better readability. Is this possible using backticks, or will I need to use concatenation.

Thanks in advance.

const testFunc = () => {
    console.log(`This is line One,
this is line Two`); //Outputs line by line.
}

testFunc();

const testFuncTwo = () => {
    console.log(`This is line One,
    this is line two`); //Cleaner, but the second line starts after the indentation. 
}

testFuncTwo();
like image 719
CantV Avatar asked Sep 21 '26 22:09

CantV


1 Answers

You can use an ES6 tag to remove indentation from your multi-line string.

In this example I’m using the dedent npm package, but there are several others that do the same:

// Commented-out for browser compatibility; un-comment for node.js
// const dedent = require('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())
<script src="https://unpkg.com/[email protected]/dist/dedent.js"></script>
like image 52
AndreasPizsa Avatar answered Sep 24 '26 11:09

AndreasPizsa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!