Create a multiline string in JavaScript
Today, you will learn how to create a multiline string in JavaScript. There are three different ways to write a mulitline string in JavaScript.
Checkout more articles on JavaScript
Ways to create a multiline string in JavaScript
1. Using + operator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // using the + operator const action = 'www.cluemediator.com\n' + 'Like us on Facebook\n' + 'Follow us on Twitter\n' + 'Follow us on GitHub\n' + 'Subscribe us on YouTube\n' + 'Join us on Telegram\n' + 'Follow us on Instagram'; console.log(action); /* www.cluemediator.com Like us on Facebook Follow us on Twitter Follow us on GitHub Subscribe us on YouTube Join us on Telegram Follow us on Instagram */ |
The +
operator and \n
are used to produce a multiline string in the above example. The line is broken by the escape character \n
.
2. Using \ operator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // using the \ operator const action = 'www.cluemediator.com\n\ Like us on Facebook\n\ Follow us on Twitter\n\ Follow us on GitHub\n\ Subscribe us on YouTube\n\ Join us on Telegram\n\ Follow us on Instagram'; console.log(action); /* www.cluemediator.com Like us on Facebook Follow us on Twitter Follow us on GitHub Subscribe us on YouTube Join us on Telegram Follow us on Instagram */ |
In the above example, a multiline string is created using .
\n
is used to break the line.
3. Using template literal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // using the template literal const action = `www.cluemediator.com Like us on Facebook Follow us on Twitter Follow us on GitHub Subscribe us on YouTube Join us on Telegram Follow us on Instagram`; console.log(action); /* www.cluemediator.com Like us on Facebook Follow us on Twitter Follow us on GitHub Subscribe us on YouTube Join us on Telegram Follow us on Instagram */ |
In the above example, the template literal
is used to write multiline strings. The template literal was introduced in the newer version of JavaScript (ES6).
That’s it for today.
Thank you for reading. Happy Coding..!! đŸ™‚