Create a multiline string in JavaScript
📅May 7, 2022
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
- How to capture Enter key press in JavaScript
- How to highlight searched text using JavaScript
- How to set an HTML element’s class using JavaScript
- How to create an auto-resize Textarea in JavaScript
Ways to create a multiline string in JavaScript
1. Using + operator
// 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
// 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
// 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..!! 🙂