[javascript] Creating multiline strings in JavaScript

I have the following code in Ruby. I want to convert this code into JavaScript. what's the equivalent code in JS?

text = <<"HERE"
This
Is
A
Multiline
String
HERE

This question is related to javascript string multiline heredoc

The answer is


Please for the love of the internet use string concatenation and opt not to use ES6 solutions for this. ES6 is NOT supported all across the board, much like CSS3 and certain browsers being slow to adapt to the CSS3 movement. Use plain ol' JavaScript, your end users will thank you.

Example:

var str = "This world is neither flat nor round. "+ "Once was lost will be found";


If you happen to be running in Node only, you could use the fs module to read in the multi-line string from a file:

var diagram;
var fs = require('fs');
fs.readFile( __dirname + '/diagram.txt', function (err, data) {
  if (err) {
    throw err; 
  }
  diagram = data.toString();
});

Easiest way to make multiline strings in Javascrips is with the use of backticks ( `` ). This allows you to create multiline strings in which you can insert variables with ${variableName}.

Example:

_x000D_
_x000D_
let name = 'Willem'; _x000D_
let age = 26;_x000D_
_x000D_
let multilineString = `_x000D_
my name is: ${name}_x000D_
_x000D_
my age is: ${age}_x000D_
`;_x000D_
_x000D_
console.log(multilineString);
_x000D_
_x000D_
_x000D_

compatibility :

  • It was introduces in ES6//es2015
  • It is now natively supported by all major browser vendors (except internet explorer)

Check exact compatibility in Mozilla docs here


My version of array-based join for string concat:

var c = []; //c stands for content
c.push("<div id='thisDiv' style='left:10px'></div>");
c.push("<div onclick='showDo(\'something\');'></div>");
$(body).append(c.join('\n'));

This has worked well for me, especially as I often insert values into the html constructed this way. But it has lots of limitations. Indentation would be nice. Not having to deal with nested quotation marks would be really nice, and just the bulkyness of it bothers me.

Is the .push() to add to the array taking up a lot of time? See this related answer:

(Is there a reason JavaScript developers don't use Array.push()?)

After looking at these (opposing) test runs, it looks like .push() is fine for string arrays which will not likely grow over 100 items - I will avoid it in favor of indexed adds for larger arrays.


I solved this by outputting a div, making it hidden, and calling the div id by jQuery when I needed it.

e.g.

<div id="UniqueID" style="display:none;">
     Strings
     On
     Multiple
     Lines
     Here
</div>

Then when I need to get the string, I just use the following jQuery:

$('#UniqueID').html();

Which returns my text on multiple lines. If I call

alert($('#UniqueID').html());

I get:

enter image description here


The Rule is: when inside a string, use \n wherever you want a new line; you do not have to put a space before or after the \n, JavaScript's interpreter is smart enough to know how long the unprintable character representation is.


the pattern text = <<"HERE" This Is A Multiline String HERE is not available in js (I remember using it much in my good old Perl days).

To keep oversight with complex or long multiline strings I sometimes use an array pattern:

var myString = 
   ['<div id="someId">',
    'some content<br />',
    '<a href="#someRef">someRefTxt</a>',
    '</div>'
   ].join('\n');

or the pattern anonymous already showed (escape newline), which can be an ugly block in your code:

    var myString = 
       '<div id="someId"> \
some content<br /> \
<a href="#someRef">someRefTxt</a> \
</div>';

Here's another weird but working 'trick'1:

var myString = (function () {/*
   <div id="someId">
     some content<br />
     <a href="#someRef">someRefTxt</a>
    </div>        
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];

external edit: jsfiddle

ES20xx supports spanning strings over multiple lines using template strings:

let str = `This is a text
    with multiple lines.
    Escapes are interpreted,
    \n is a newline.`;
let str = String.raw`This is a text
    with multiple lines.
    Escapes are not interpreted,
    \n is not a newline.`;

1 Note: this will be lost after minifying/obfuscating your code


My extension to https://stackoverflow.com/a/15558082/80404. It expects comment in a form /*! any multiline comment */ where symbol ! is used to prevent removing by minification (at least for YUI compressor)

Function.prototype.extractComment = function() {
    var startComment = "/*!";
    var endComment = "*/";
    var str = this.toString();

    var start = str.indexOf(startComment);
    var end = str.lastIndexOf(endComment);

    return str.slice(start + startComment.length, -(str.length - end));
};

Example:

var tmpl = function() { /*!
 <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
    </ul>
 </div>
*/}.extractComment();

This works in IE, Safari, Chrome and Firefox:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div class="crazy_idea" thorn_in_my_side='<table  border="0">
                        <tr>
                            <td ><span class="mlayouttablecellsdynamic">PACKAGE price $65.00</span></td>
                        </tr>
                    </table>'></div>
<script type="text/javascript">
    alert($(".crazy_idea").attr("thorn_in_my_side"));
</script>

You can do this...

var string = 'This is\n' +
'a multiline\n' + 
'string';

This is one fairly economical approach, at least in terms of the source code:

function s() {
    var args = [],index;
    for (index = 0; index< arguments.length; index++) {
        args.push (arguments [index]);
    }
    return args.join ("\n");
}
console.log (s (
    "This is the first line",
    "and this is the second",
    "finally a third"
));

function s() {return arguments.join ("\n")} 

would be nicer of course if the "arguments" property were a proper array.

A second version might use "" to do the join for cases when you want to control the line breaks in a very long string.


The ES6 way of doing it would be by using template literals:

const str = `This 

is 

a

multiline text`; 

console.log(str);

More reference here


I came up with this very jimmy rigged method of a multi lined string. Since converting a function into a string also returns any comments inside the function you can use the comments as your string using a multilined comment /**/. You just have to trim off the ends and you have your string.

var myString = function(){/*
    This is some
    awesome multi-lined
    string using a comment 
    inside a function 
    returned as a string.
    Enjoy the jimmy rigged code.
*/}.toString().slice(14,-3)

alert(myString)

ES6 Update:

As the first answer mentions, with ES6/Babel, you can now create multi-line strings simply by using backticks:

const htmlString = `Say hello to 
multi-line
strings!`;

Interpolating variables is a popular new feature that comes with back-tick delimited strings:

const htmlString = `${user.name} liked your post about strings`;

This just transpiles down to concatenation:

user.name + ' liked your post about strings'

Original ES5 answer:

Google's JavaScript style guide recommends to use string concatenation instead of escaping newlines:

Do not do this:

var myString = 'A rather long string of English text, an error message \
                actually that just keeps going and going -- an error \
                message to make the Energizer bunny blush (right through \
                those Schwarzenegger shades)! Where was I? Oh yes, \
                you\'ve got an error and all the extraneous whitespace is \
                just gravy.  Have a nice day.';

The whitespace at the beginning of each line can't be safely stripped at compile time; whitespace after the slash will result in tricky errors; and while most script engines support this, it is not part of ECMAScript.

Use string concatenation instead:

var myString = 'A rather long string of English text, an error message ' +
               'actually that just keeps going and going -- an error ' +
               'message to make the Energizer bunny blush (right through ' +
               'those Schwarzenegger shades)! Where was I? Oh yes, ' +
               'you\'ve got an error and all the extraneous whitespace is ' +
               'just gravy.  Have a nice day.';

Also do note that, when extending string over multiple lines using forward backslash at end of each line, any extra characters (mostly spaces, tabs and comments added by mistake) after forward backslash will cause unexpected character error, which i took an hour to find out

var string = "line1\  // comment, space or tabs here raise error
line2";

Just tried the Anonymous answer and found there's a little trick here, it doesn't work if there's a space after backslash \
So the following solution doesn't work -

var x = { test:'<?xml version="1.0"?>\ <-- One space here
            <?mso-application progid="Excel.Sheet"?>' 
};

But when space is removed it works -

var x = { test:'<?xml version="1.0"?>\<-- No space here now
          <?mso-application progid="Excel.Sheet"?>' 
};

alert(x.test);?

Hope it helps !!


If you're willing to use the escaped newlines, they can be used nicely. It looks like a document with a page border.

enter image description here


The equivalent in javascript is:

var text = `
This
Is
A
Multiline
String
`;

Here's the specification. See browser support at the bottom of this page. Here are some examples too.


Exact

Ruby produce: "This\nIs\nA\nMultiline\nString\n" - below JS produce exact same string

_x000D_
_x000D_
text = `This
Is
A
Multiline
String
`

// TEST
console.log(JSON.stringify(text));
console.log(text);
_x000D_
_x000D_
_x000D_

This is improvement to Lonnie Best answer because new-line characters in his answer are not exactly the same positions as in ruby output


i found a more elegant solution, maybe a little non-topic related because it uses PHP, but im sure it will be useful and cuteness* for some of yours...

this javascript code should stay inside script tags

var html=<?php echo json_encode("

        <div class=container>
            <div class=area1>
                xxx
            </div>
            <div class=area2>
                ".$someVar."
            </div>
        </div>

"); ?>

in your output html you will see something like

var html="\r\n\r\n\t\t\t<div class=container>\r\n\t\t\t\t<div class=area1>\r\n\t\t\t\t\txxx\r\n\t\t\t\t<\/div>\r\n\t\t\t\t<div class=area2>\r\n\t\t\t\t\t44\r\n\t\t\t\t<\/div>\r\n\t\t\t<\/div>\r\n\r\n\t\t";  

 


and et voilĂ !, it gives you code readability in your file.

pD: this sample uses json_encode() PHP function, but certainly there are function equivalents for ASP, Ruby and JSP langs.

pD: however, this solution have his limitations too, one of them is you cannot use javascript variables inside the encapsulated code.


You can use += to concatenate your string, seems like no one answered that, which will be readable, and also neat... something like this

var hello = 'hello' +
            'world' +
            'blah';

can be also written as

var hello = 'hello';
    hello += ' world';
    hello += ' blah';

console.log(hello);

You can use TypeScript (JavaScript SuperSet), it supports multiline strings, and transpiles back down to pure JavaScript without overhead:

var templates = {
    myString: `this is
a multiline
string` 
}

alert(templates.myString);

If you'd want to accomplish the same with plain JavaScript:

var templates = 
{
 myString: function(){/*
    This is some
    awesome multi-lined
    string using a comment 
    inside a function 
    returned as a string.
    Enjoy the jimmy rigged code.
*/}.toString().slice(14,-3)

}
alert(templates.myString)

Note that the iPad/Safari does not support 'functionName.toString()'

If you have a lot of legacy code, you can also use the plain JavaScript variant in TypeScript (for cleanup purposes):

interface externTemplates
{
    myString:string;
}

declare var templates:externTemplates;

alert(templates.myString)

and you can use the multiline-string object from the plain JavaScript variant, where you put the templates into another file (which you can merge in the bundle).

You can try TypeScript at
http://www.typescriptlang.org/Playground


You have to use the concatenation operator '+'.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <p id="demo"></p>
    <script>
        var str = "This "
                + "\n<br>is "
                + "\n<br>multiline "
                + "\n<br>string.";
        document.getElementById("demo").innerHTML = str;
     </script>
</body>
</html>

By using \n your source code will look like -

This 
 <br>is
 <br>multiline
 <br>string.

By using <br> your browser output will look like -

This
is
multiline
string.

ES6 allows you to use a backtick to specify a string on multiple lines. It's called a Template Literal. Like this:

var multilineString = `One line of text
    second line of text
    third line of text
    fourth line of text`;

Using the backtick works in NodeJS, and it's supported by Chrome, Firefox, Edge, Safari, and Opera.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals


There are multiple ways to achieve this

1. Slash concatenation

  var MultiLine=  '1\
    2\
    3\
    4\
    5\
    6\
    7\
    8\
    9';

2. regular concatenation

var MultiLine = '1'
+'2'
+'3'
+'4'
+'5';

3. Array Join concatenation

var MultiLine = [
'1',
'2',
'3',
'4',
'5'
].join('');

Performance wise, Slash concatenation (first one) is the fastest.

Refer this test case for more details regarding the performance

Update:

With the ES2015, we can take advantage of its Template strings feature. With it, we just need to use back-ticks for creating multi line strings

Example:

 `<h1>{{title}}</h1>
  <h2>{{hero.name}} details!</h2>
  <div><label>id: </label>{{hero.id}}</div>
  <div><label>name: </label>{{hero.name}}</div>
  `

There's this library that makes it beautiful:

https://github.com/sindresorhus/multiline

Before

var str = '' +
'<!doctype html>' +
'<html>' +
'   <body>' +
'       <h1>? unicorns</h1>' +
'   </body>' +
'</html>' +
'';

After

var str = multiline(function(){/*
<!doctype html>
<html>
    <body>
        <h1>? unicorns</h1>
    </body>
</html>
*/});

You can have multiline strings in pure JavaScript.

This method is based on the serialization of functions, which is defined to be implementation-dependent. It does work in the most browsers (see below), but there's no guarantee that it will still work in the future, so do not rely on it.

Using the following function:

function hereDoc(f) {
  return f.toString().
      replace(/^[^\/]+\/\*!?/, '').
      replace(/\*\/[^\/]+$/, '');
}

You can have here-documents like this:

var tennysonQuote = hereDoc(function() {/*!
  Theirs not to make reply,
  Theirs not to reason why,
  Theirs but to do and die
*/});

The method has successfully been tested in the following browsers (not mentioned = not tested):

  • IE 4 - 10
  • Opera 9.50 - 12 (not in 9-)
  • Safari 4 - 6 (not in 3-)
  • Chrome 1 - 45
  • Firefox 17 - 21 (not in 16-)
  • Rekonq 0.7.0 - 0.8.0
  • Not supported in Konqueror 4.7.4

Be careful with your minifier, though. It tends to remove comments. For the YUI compressor, a comment starting with /*! (like the one I used) will be preserved.

I think a real solution would be to use CoffeeScript.

ES6 UPDATE: You could use backtick instead of creating a function with a comment and running toString on the comment. The regex would need to be updated to only strip spaces. You could also have a string prototype method for doing this:

let foo = `
  bar loves cake
  baz loves beer
  beer loves people
`.removeIndentation()

Someone should write this .removeIndentation string method... ;)


Downvoters: This code is supplied for information only.

This has been tested in Fx 19 and Chrome 24 on Mac

DEMO

_x000D_
_x000D_
var new_comment; /*<<<EOF _x000D_
    <li class="photobooth-comment">_x000D_
       <span class="username">_x000D_
          <a href="#">You</a>:_x000D_
       </span>_x000D_
       <span class="comment-text">_x000D_
          $text_x000D_
       </span> _x000D_
       @<span class="comment-time">_x000D_
          2d_x000D_
       </span> ago_x000D_
    </li>_x000D_
EOF*/_x000D_
// note the script tag here is hardcoded as the FIRST tag _x000D_
new_comment=document.currentScript.innerHTML.split("EOF")[1]; _x000D_
document.querySelector("ul").innerHTML=new_comment.replace('$text','This is a dynamically created text');
_x000D_
<ul></ul>
_x000D_
_x000D_
_x000D_


to sum up, I have tried 2 approaches listed here in user javascript programming (Opera 11.01):

So I recommend the working approach for Opera user JS users. Unlike what the author was saying:

It doesn't work on firefox or opera; only on IE, chrome and safari.

It DOES work in Opera 11. At least in user JS scripts. Too bad I can't comment on individual answers or upvote the answer, I'd do it immediately. If possible, someone with higher privileges please do it for me.


I think I discovered another way to do it inline without any invasive syntax on every line. Use Javascript's ability to convert a function to string and create a multiline comment with the /**/ syntax then remove the "function() {/*\n" and "\n*/}".

var multiline = function(string) { return string.toString().replace(/(^[^\n]*\n)|(\n\*\/\})/g, ""); };

console.log(multiline(function() {/*
Hello world!
I'm a multiline string!

Tada!
*/}));

The only pitfall I can see in this is the syntax highlighting.

EDIT: Had I scrolled down a little more, I would have seen this answer doing exactly the same thing: https://stackoverflow.com/a/5571069/916553


It's not extremely elegant but it's clean enough for me:

var myString = "First line" + "\n";
var myString = myString + "Second line" + "\n";
var myString = myString + "Third line" + "\n";

I'm surprised I didn't see this, because it works everywhere I've tested it and is very useful for e.g. templates:

<script type="bogus" id="multi">
    My
    multiline
    string
</script>
<script>
    alert($('#multi').html());
</script>

Does anybody know of an environment where there is HTML but it doesn't work?


I program this way:

sys = {
    layout: null,
    makeLayout: function (obCLS) {
        this.layout = $('<div />').addClass('editor').appendTo($(obCLS)).append(

            /* Cargador */
            /* @this.layout.find('> div:nth-of-child(1)'); */
            '<div>' +
            '   <p>Seleccione la imagen que desea procesar.</p>' +
            '   <input type="button" value="Seleccionar" class="btn btn-xlarge btn-success" />' +
            '   <span></span>' +
            '</div>' +

            /* Cargador - Progreso */
            /* @this.layout.find('> div:nth-of-child(2)'); */
            '<div>' +
            '   <div>' +
            '       <div></div>' +
            '       <div>' +
            '           <div></div>' +
            '       </div>' +
            '   </div>' +
            '</div>' +

            /* Editor */
            /* @this.layout.find('> div:nth-of-child(3)');
             * @sidebar = this.layout.find('> div:nth-of-child(3) > div > div > div:nth-of-type(1)');
             * @body    = this.layout.find('> div:nth-of-child(3) > div > div > div:nth-of-type(2) > div'); */
            '<div>' +
            '   <div>' +
            '       <div>' +
            '           <div></div>' +
            '           <div>' +
            '               <div></div>' +
            '           </div>' +
            '       </div>' +
            '   </div>' +
            '</div>'
        );
    }
}

sys.makeLayout('#div');

I think this workaround should work in IE, Chrome, Firefox, Safari, Opera -

Using jQuery :

<xmp id="unique_id" style="display:none;">
  Some plain text
  Both type of quotes :  " ' " And  ' " '
  JS Code : alert("Hello World");
  HTML Code : <div class="some_class"></div>
</xmp>
<script>
   alert($('#unique_id').html());
</script>

Using Pure Javascript :

<xmp id="unique_id" style="display:none;">
  Some plain text
  Both type of quotes :  " ' " And  ' " '
  JS Code : alert("Hello World");
  HTML Code : <div class="some_class"></div>
</xmp>
<script>
   alert(document.getElementById('unique_id').innerHTML);
</script>

Cheers!!


I like this syntax and indendation:

string = 'my long string...\n'
       + 'continue here\n'
       + 'and here.';

(but actually can't be considered as multiline string)


Updated for 2015: it's six years later now: most people use a module loader, and the main module systems each have ways of loading templates. It's not inline, but the most common type of multiline string are templates, and templates should generally be kept out of JS anyway.

require.js: 'require text'.

Using require.js 'text' plugin, with a multiline template in template.html

var template = require('text!template.html')

NPM/browserify: the 'brfs' module

Browserify uses a 'brfs' module to load text files. This will actually build your template into your bundled HTML.

var fs = require("fs");
var template = fs.readFileSync(template.html', 'utf8');

Easy.


You can use tagged templates to make sure you get the desired output.

For example:

// Merging multiple whitespaces and trimming the output

const t = (strings) => { return strings.map((s) => s.replace(/\s+/g, ' ')).join("").trim() }
console.log(t`
  This
  Is
  A
  Multiline
  String
`);
// Output: 'This Is A Multiline String'

// Similar but keeping whitespaces:

const tW = (strings) => { return strings.map((s) => s.replace(/\s+/g, '\n')).join("").trim() }
console.log(tW`
  This
  Is
  A
  Multiline
  String
`);
// Output: 'This\nIs\nA\nMultiline\nString'

Using script tags:

  • add a <script>...</script> block containing your multiline text into head tag;
  • get your multiline text as is... (watch out for text encoding: UTF-8, ASCII)

    <script>
    
        // pure javascript
        var text = document.getElementById("mySoapMessage").innerHTML ;
    
        // using JQuery's document ready for safety
        $(document).ready(function() {
    
            var text = $("#mySoapMessage").html(); 
    
        });
    
    </script>
    
    <script id="mySoapMessage" type="text/plain">
    
        <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="...">
           <soapenv:Header/>
           <soapenv:Body>
              <typ:getConvocadosElement>
                 ...
              </typ:getConvocadosElement>
           </soapenv:Body>
        </soapenv:Envelope>
    
        <!-- this comment will be present on your string -->
        //uh-oh, javascript comments...  SOAP request will fail 
    
    
    </script>
    

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to multiline

Way to create multiline comments in Bash? How to get multiline input from user R: "Unary operator error" from multiline ggplot2 command Can a JSON value contain a multiline string PHP multiline string with PHP Pythonic way to create a long multi-line string How do I create a multiline Python string with inline variables? How do you write multiline strings in Go? Multiline TextView in Android? What is the proper way to format a multi-line dict in Python?

Examples related to heredoc

How to cat <<EOF >> a file containing code? here-document gives 'unexpected end of file' error What is the advantage of using heredoc in PHP? Using variables inside a bash heredoc How can I write a heredoc to a file in Bash script? How does "cat << EOF" work in bash? Executing multi-line statements in the one-line command-line? How to assign a heredoc value to a variable in Bash? Creating multiline strings in JavaScript