Wrap long template literal line to multiline without creating a new line in the string

后端 未结 9 1385
谎友^
谎友^ 2020-12-01 02:40

In es6 template literals, how can one wrap a long template literal to multiline without creating a new line in the string?

For example, if you do this:



        
相关标签:
9条回答
  • 2020-12-01 02:53

    Use the old and the new. Template literals are great but if you want to avoid lengthy literals so as to have compact lines of code, concatenate them and ESLint won't cause a fuss.

    const text = `a very long string that just continues`
      +` and continues and continues`;
    console.log(text);
    
    0 讨论(0)
  • 2020-12-01 02:55

    EDIT: I've made an tiny NPM module with this utility. It works on web and in Node and I highly recommend it over the code in my below answer as it's far more robust. It also allows for preserving newlines in the result if you manually input them as \n, and provides functions for when you already use template literal tags for something else: https://github.com/iansan5653/compress-tag


    I know I'm late to answer here, but the accepted answer still has the drawback of not allowing indents after the line break, which means you still can't write very nice-looking code just by escaping newlines.

    Instead, why not use a tagged template literal function?

    function noWhiteSpace(strings, ...placeholders) {
      // Build the string as normal, combining all the strings and placeholders:
      let withSpace = strings.reduce((result, string, i) => (result + placeholders[i - 1] + string));
      let withoutSpace = withSpace.replace(/\s\s+/g, ' ');
      return withoutSpace;
    }
    

    Then you can just tag any template literal you want to have line breaks in:

    let myString = noWhiteSpace`This is a really long string, that needs to wrap over
        several lines. With a normal template literal you can't do that, but you can 
        use a template literal tag to allow line breaks and indents.`;
    

    This does have the drawback of possibly having unexpected behavior if a future developer isn't used to the tagged template syntax or if you don't use a descriptive function name, but it feels like the cleanest solution for now.

    0 讨论(0)
  • 2020-12-01 02:56

    This is an old one. But it came up. If you leave any spaces in the editor it will put them in there.

    if
      const text = `a very long string that just continues\
      and continues and continues`;
    

    just do the normal + symbol

    if
      const text = `a very long string that just continues` +
      `and continues and continues`;
    
    0 讨论(0)
  • 2020-12-01 02:57

    I'm a bit late to the party, but for any future visits on this question, I found this soultion the most optimal for my use case.

    I'm running a Node.js server and wanted to return html in string format, this is how I solved it:


    My response object:

    const httpResponse = {
        message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent ultrices et odio eget blandit. Donec non tellus diam. Duis massa augue, cursus a ornare vel, pharetra ac turpis.',
        html: `
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
            <p>Praesent ultrices et odio eget blandit.</p>
            <ul>
                <li>Donec non tellus diam</li>
                <li>Duis massa augue</li>
            </ul>
        `,
    }
    

    This would translate into the following when sending a http request:

    {
        "message": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent ultrices et odio eget blandit. Donec non tellus diam. Duis massa augue, cursus a ornare vel, pharetra ac turpis.",
        "html": "\n\t\t<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>\n\t\t<p>Praesent ultrices et odio eget blandit.</p>\n\t\t<ul>\n\t\t\t<li>Donec non tellus diam</li>\n\t\t\t<li>Duis massa augue</li>\n\t\t</ul>\n\t"
    }
    

    This is of course ugly and hard to work with. So before I sending the http I trim every line of the string.

    httpResponse.html = httpResponse.html.split('\n').map(line => line.trim()).join('')
    

    This is what the result looks like after that simple line of code.

    {
        "message": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent ultrices et odio eget blandit. Donec non tellus diam. Duis massa augue, cursus a ornare vel, pharetra ac turpis.",
        "html": "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p><p>Praesent ultrices et odio eget blandit.</p><ul><li>Donec non tellus diam</li><li>Duis massa augue</li></ul>"
    }
    
    0 讨论(0)
  • 2020-12-01 02:58

    You could just eat the line breaks inside your template literal.

    // Thanks to https://twitter.com/awbjs for introducing me to the idea
    // here: https://esdiscuss.org/topic/multiline-template-strings-that-don-t-break-indentation
    
    const printLongLine = continues => {
        const text = `a very long string that just ${continues}${''
                     } and ${continues} and ${continues}`;
        return text;
    }
    console.log(printLongLine('continues'));

    0 讨论(0)
  • 2020-12-01 02:59

    Another option is to use Array.join, like so:

    [
        'This is a very long string. ',
        'It just keeps going ',
        'and going ',
        'and going ',
        'and going ',
        'and going ',
        'and going ',
        'and going',
    ].join('')
    
    0 讨论(0)
提交回复
热议问题