javascriptstringconstantsline

How to break a string so it is not all in one line in my source code?


say I have the following string in javascript:

const myStr = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididuntut labore et dolore magna aliqua. Vel facilisis volutpat est velit. Enim nunc faucibus a pellentesque sit." but everytime I try to break it so it occupies two lines in atom so I can see it all, it is not one string anymore. How can I do it properly?


Solution

  • Depending on how it is used, you can use javascript template strings or just concatenate.

    To use template strings, you simply wrap your text in backticks. This also gives the added benefit of allowing string interpolation with variables. The only downside is that it will preserve white space.

    Eg:

    const name = 'Jen';
    const myLongStr = `Hello ${name}, This is a super long string that
        needs to break between lines. It's not that big of an issue
        depending on the use case.`
    const strWithHtml = `<p>Hello <strong>${name}</strong>,</p>
                         <p>This is a paragraph, demostrating HTML usage.</p>`
    

    The other option, as mentioned in other answers is simple string concatenation.

    Eg:

    const myLongStr = 'Lorem ipsum dolor sit amet, consectetur ' +
                      'adipiscing elit, sed do eiusmod tempor incididuntut ' +
                      'labore et dolore magna aliqua. Vel facilisis volutpat ' +
                      'est velit. Enim nunc faucibus a pellentesque sit.';
    

    Depending on your use case, choosing one of these should work well.

    Due to Javascript allowing you to break things onto multiple lines as long as a line doesn't end with a semicolon, this becomes quite easy.