Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating multiline strings in JavaScript

I have the following code in Ruby. I want to convert this code into JavaScript. What is the equivalent code in JS?

text = <<"HERE" This Is A Multiline String HERE 
like image 348
Newy Avatar asked Apr 30 '09 02:04

Newy


People also ask

How do I create a multiline string in JavaScript?

There are three ways to create a multiline string in JavaScript. We can use the concatenation operator, a new line character (\n), and template literals. Template literals were introduced in ES6. They also let you add the contents of a variable into a string.

What is the delimiter for multi line strings in JavaScript?

Method 1: Multiline-strings are created by using template literals. The strings are delimited using backticks, unlike normal single/double quotes delimiter.

How do you write multi line strings in template literals?

HTML. Example 2: If you use double/single quote to write multiline string then we use the newline character (\n). Use an extra backslash ( \ ) after every newline character (\n), this backslash tells the JavaScript engine that the string is not over yet.


1 Answers

Update:

ECMAScript 6 (ES6) introduces a new type of literal, namely template literals. They have many features, variable interpolation among others, but most importantly for this question, they can be multiline.

A template literal is delimited by backticks:

var html = `   <div>     <span>Some HTML here</span>   </div> `; 

(Note: I'm not advocating to use HTML in strings)

Browser support is OK, but you can use transpilers to be more compatible.


Original ES5 answer:

Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close:

"foo \ bar" 
like image 59
Anonymous Avatar answered Oct 03 '22 17:10

Anonymous