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();
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With