问题
ESLint: Line 403 exceeds the maximum line length of 120 (max-len)
I have a long string, which I built using ES6 template strings, but I want it to be without line breaks:
var string = `Let me be the 'throws Exception’ to your 'public static void
main (String[] args)’. I will accept whatever you give me my ${love}.`
console.log(string);
Result:
Let me be the 'throws Exception’ to your 'public static void
main (String[] args)’. I will accept whatever you give me xxx.
My expectation:
Let me be the 'throws Exception’ to your 'public static void main (String[] args)’. I will accept whatever you give me xxx.
Requirements:
I cannot disable the eslint rule, as enforcement is necessary.
I cannot put the data in a separate file, as the data is dynamic.
I cannot concatenate multiple shorter strings, since that is too much work.
回答1:
This is expected behaviour. One of the important problems that template literals solve is multiline strings:
Any new line characters inserted in the source are part of the template literal.
If the string needs to be processed further, this can be done with other JS features, like regular expressions:
var string = `Let me be the 'throws Exception’ to your 'public static void
main (String[] args)’. I will accept whatever you give me.`
.replace(/[\n\r]+ */g, ' ');
String.raw is built-in function to transform template literals. It's possible to use tag function to provide custom behaviour to template literals. It should be noticed that String.raw
differs from default template transformer in terms of how it processes special characters. If they are used in a string, they should be additionally processed with unescape-js or similar helper function.
function singleLine(strsObj, ...values) {
const strs = strsObj.raw
.map(str => str.replace(/[\n\r]+ */g, ' '))
.map(unescapeSpecialChars);
return String.raw(
{raw: strs },
...values
);
}
var string = singleLine`Let me be the 'throws Exception’ to your 'public static void
main (String[] args)’. I will accept whatever you give me.`;
回答2:
A good way of reaching your purpose is to to join an array of strings:
var string = [
`Let me be the 'throws Exception’ to your 'public static void`,
`main (String[] args)’. I will accept whatever you give me my ${love}.`
].join(' ');
回答3:
If your problem is just the EsLint error you can ignore it for this specific line using this feature: /* eslint-disable max-len */
In my honest opinion is the best approach because you are not giving extra complexity.
If you start using regex or concatenation you are changing the purpose of template string by not using concatenation...
回答4:
Use string concatenation as well:
var string=`abc`+`def`;
console.log(string);
yields:
abcdef
来源:https://stackoverflow.com/questions/46379115/prevent-line-breaks-in-es6-template-string