While writing amazing web applications in HTML, CSS and JavaScript you may come across a situation where you have to store a multi-line string in a variable in your JavaScript. In this post we will be covering three different ways of implementing multi-line string in JavaScript out of which one is based on the latest ES6 (ECMAScript 6) and the other two solutions are traditional solutions based on older JavaScript versions.
So let's see them one by one.
ES6 Multi-line Strings - Template literals
In the ES6 specification, the concept of Template literals is introduced which uses backticks to define multi-line strings and for expression evaluation too in a string (more like we do in Python using format method).
var myStr = `This is my
multiline String
which is amazing`;
Some online JavaScript validators may show error in this syntax but you cna ignore them as they are the ones who are not updated yet as per the latest ES6 specifications.
ES5 - Using backslash
By adding a backslash at the end of every line in a multiline string works if you want to define a multiline string. This can be a bit confusing as we are adding a special symbol to escape the new line character.
var myStr = "This is my \
multiline String \
which is amazing";
By Concatenating multiple lines
If you are old fashioned and like to write code that every one understands, you can implement a multi-line string using normal string concatenation technique where you concatenate each line of the multi-line string to the variable. Below we have a code example for it:
var myStr = "This is my" +
" multiline String " +
" which is amazing";
For concatenating strings, we use the +
operator.
Time for an Example
Let's see the above code running in a simple code example.
Conclusion:
There are many different ways for defining multi-line strings and you can opt for any one. We would recommend you to go for the ES6 approach, as that is the latest one.
You may also like: