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

后端 未结 9 1389
谎友^
谎友^ 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: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: `
            

    Lorem ipsum dolor sit amet, consectetur adipiscing elit.

    Praesent ultrices et odio eget blandit.

    • Donec non tellus diam
    • Duis massa augue
    `, }

    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

    Lorem ipsum dolor sit amet, consectetur adipiscing elit.

    \n\t\t

    Praesent ultrices et odio eget blandit.

    \n\t\t
      \n\t\t\t
    • Donec non tellus diam
    • \n\t\t\t
    • Duis massa augue
    • \n\t\t
    \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": "

    Lorem ipsum dolor sit amet, consectetur adipiscing elit.

    Praesent ultrices et odio eget blandit.

    • Donec non tellus diam
    • Duis massa augue
    " }

提交回复
热议问题