Use the JavaScript ES6 Backtick (Template literal) feature to write multiline strings in HTML code

The ES6 specification of JavaScript and of course the TypeScript language, provide us the template literal syntax (the `` characters). With the template literals we can write multiline strings in JavaScript without having to use the old syntax. Take a look at the following example:

    var testString = "Lorem ipsum dolor sit amet, \
            \nconsetetur sadipscing elitr, \
            \nsed diam nonumy eirmod tempor \
            \ninvidunt ut labore et dolore";
 

As you can see with the old syntax we have to use the \ sign at the end of each line, except the last one. Apart from that at the beginning of each line we have to use the \n newline sign. If you forget one of the two signs in one line, then this line is not going to be placed in a new separate line. You can show JavaScript strings that contain newlines in console.log or in alert.

The new ES6 syntax which uses the `` (backtick) symbols is much simpler and intuitive than the old one:

    var testString = `Lorem ipsum dolor sit amet,
            consetetur sadipscing elitr,
            sed diam nonumy eirmod tempor
            invidunt ut labore et dolore`;
 

As you can see in both cases, the extra indentation at the beginning of each line does not add any white space in the string.

As I wrote before, the newlines are only added in both cases when the string is used inside JavaScript context (console.log, alert, etc.).

If you want to add and show these strings in your HTML code then you have to replace all occurrences of the \n (newline) sign with the <br/> HTML-element. To achieve that you can use the following code:

    testString = testString.replace(/\n/g, "<br>");
 

Then you can add the string into a div by using the innerHTML property of this HTML element

comments powered by Disqus