Issue #247 (ES5 Multi-line Strings, CSS/HTML, Text Editors, Build)04/12/18
Before ES6's template literals were introduced, doing multi-line strings in JavaScript was a little messy, but possible. Oddly, for the longest time, I always thought the following was perfectly valid JavaScript:
var message = "This is a \
multi-line string.";
|
The idea here is that, for whatever reason, I want my string to break onto multiple lines without closing the quotes. Inserting the backslash at the end of the line allows me to get away with this in pre-ES6 code.
But the fact that all browsers basically handled this the same way (i.e. allowing multi-line strings to work) was not a language feature, but a bug. And many style guides and linters, as I'm sure many of you have learned, will warn about this. For example,
see this JSFiddle that gives a JSHint warning: "Bad escaping of EOL. Use option multistr if needed."
So if you don't want to have a warning like that in your linting workflow when using pre-ES6 multi-line strings, you can do this:
/*jshint multistr: true */
var message = "This is a \
multi-line string.";
|
Try on JSFiddle
Of course, this doesn't solve the problem, but it prevents the warning and will likely make you feel superficially warm and fuzzy inside. You can also do something similar in linters with config options, rather than as a JavaScript comment.
Google's JavaScript Style Guide
advises against this and recommends using regular string concatenation to mimic the same idea:
let message = "This is a " +
"multi-line string.";
|
One final point that you may not have known with regards to these old-school multi-line strings: If you put a space after the backslash, the code will fail. Google's guide warns specifically about this.
There are other old solutions to this problem, which you can read about in
this old and lengthy Stack Overflow thread. Some of the answers are quite creative (e.g. using an array to mimic it) and you also get a pretty good history lesson on bugs and browser support in relation to this topic.
As mentioned, template literals make this basically obsolete except for legacy-based requirements. See issues
169 and
170 in the newsletter archives for a couple of tips on how to use those.
Now on to this week's tools!