According to this esdiscuss discussion, it is possible in ECMAScript 6 to define multiline strings without having to place subsequent lines of the string at the very beginning of the line.
Allen Wirfs-Brock’s post contains a code example:
var a = dontIndent `This is a template string. Even though each line is indented to keep the code neat and tidy, the white space used to indent is not in the resulting string`;
Could someone explain how this can be achieved? How to define this dontIndent
thing in order to remove the whitespace used for indentation?
Use triple quotes to create a multiline string You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.
Raw StringsThey can span multiple lines without concatenation and they don't use escaped sequences. You can use backslashes or double quotes directly.
If you prefer using [spacebar] to indent your code rather than using [tab], you can select multiple lines by holding the [alt] key and clicking on the beginning of each line you want to indent. Then, you can press [spacebar] and all the selected lines will be affected.
2020 answer: there is still nothing built into the JS stdlib to handle de-denting long lines, although TC39 has discussed adding a new template literal that handles indentation. You have 2 options presently:
dedent-js
package actually works with both tabs and spaces, dedent
is a separate package and fails on tabs: var dedent = require('dedent-js');
var text = dedent(` <div> <span>OK</span> <div> <div></div> </div> </div> `);
Will strip out the proceeding whitespace on each line and the leading carriage return. It also has more users, an issue tracker, and is more easily updated than copypasting from Stack Overflow!
The empty export...
is immediately after the carriage return, but shows up as indented.This feature is implemented by defining a custom function and then using it as a tag (dontIndent
above). The code blow is from Zenparsing's gist:
function dedent(callSite, ...args) { function format(str) { let size = -1; return str.replace(/\n(\s+)/g, (m, m1) => { if (size < 0) size = m1.replace(/\t/g, " ").length; return "\n" + m1.slice(Math.min(m1.length, size)); }); } if (typeof callSite === "string") return format(callSite); if (typeof callSite === "function") return (...args) => format(callSite(...args)); let output = callSite .slice(0, args.length + 1) .map((text, i) => (i === 0 ? "" : args[i - 1]) + text) .join(""); return format(output); }
I've successfully tested it in Firefox Nightly:
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