Search code examples
javascriptecmascript-6template-strings

Prevent line breaks in ES6 template string


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:

  1. I cannot disable the eslint rule, as enforcement is necessary.

  2. I cannot put the data in a separate file, as the data is dynamic.

  3. I cannot concatenate multiple shorter strings, since that is too much work.


Solution

  • 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.`;