ChatGPT解决这个技术问题 Extra ChatGPT

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

K
Kelderic

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"

Be warned: some browsers will insert newlines at the continuance, some will not.
Visual Studio 2010 seems to be confused by this syntax as well.
@Nate It is specified in ECMA-262 5th Edition section 7.8.4 and called LineContinuation : "A line terminator character cannot appear in a string literal, except as part of a LineContinuation to produce the empty character sequence. The correct way to cause a line terminator character to be part of the String value of a string literal is to use an escape sequence such as \n or \u000A."
I don't see why you'd do this when browsers treat it inconsistently. "line1\n" + "line2" across multiple lines is readable enough and you're guaranteed consistent behavior.
"Browser support is OK"... not supported by IE11 - not OK
D
Devin Rhode

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.';


I don't understand Google's recommendation. All browsers except extremely old ones support the backslash followed by newline approach, and will continue to do so in the future for backward compatibility. The only time you'd need to avoid it is if you needed to be sure that one and only one newline (or no newline) was added at the end of each line (see also my comment on the accepted answer).
Note that template strings aren't supported in IE11, Firefox 31, Chrome 35, or Safari 7. See kangax.github.io/compat-table/es6
@MattBrowne Google's recommendation is already documented by them, in order of importance of reasons: (1) The whitespace at the beginning of each line [in the example, you don't want that whitespace in your string but it looks nicer in the code] (2) whitespace after the slash will result in tricky errors [if you end a line with \ instead of `\` it's hard to notice] and (3) while most script engines support this, it is not part of ECMAScript [i.e. why use nonstandard features?] Remember it's a style guide, which is about making code easy to read+maintain+debug: not just "it works" correct.
amazing that after all these years string concatenation is still the best/safest/most compliant way to go with this. template literals (above answer) don't work in IE and escaping lines is just a mess that you're soon going to regret
Found out the hard way that older versions of Android do not support the backticks so if you have an Android app using the webView your backticks cause your app to not run!
K
KooiInc

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


Please don't use the array pattern. It will be slower than plain-old string concatenation in most cases.
The array pattern is more readable and the performance loss for an application is often negligible. As that perf test shows, even IE7 can do tens of thousands of operations per second.
+1 for an elegant alternative that not only works the same way in all browsers, but is also future-proof.
@KooiInc Your tests start with the array already created, that skews the results. If you add the initialization of the array, straight concatenation is faster jsperf.com/string-concat-without-sringbuilder/7 See stackoverflow.com/questions/51185/… As a trick for newlines, it may be OK, but it's definitely doing more work than it should
@BMiner: 1) "Premature optimization is the root of all evil" - Donald Knuth, and 2) 'readability' is in the eye of the beholder
g
gpl

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... ;)


What!? creating and decompiling a Function to hack a multiline comment into being a multiline string? Now that's ugly.
jsfiddle.net/fqpwf works in Chrome 13 and IE8/9, but not FF6. I hate to say it, but I like it, and if it could be an intentional feature of each browser (so that it wouldn't disappear), I'd use it.
@uosɐſ: for it to be intentional, it'd have to be in the spec; or so widespread used, that browser makers wouldn't want to remove this "accidental" feature. Thanks for the experiments though... Try some coffeescript.
a.toString().substring(15, a.toString().length-4) also works, and doesn't need to scan the entire string (although it most likely will and the counting makes it another scan anyway. Oh wel.)
Extremely handy. I'm using it for (Jasmine) unit tests, but avoiding it for production code.
5
5 revs, 2 users 97%

You can do this...

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

First example is great and simple. Much better than the \ approach as I'm not sure how browser's would handle the backslash as an escape character and as a multi-line character.
e4x.js would be the good future-proof solution
L
Luke

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)

This is absolutely terrifying. I love it (although you may need to do a regex match because I'm not sure how precise the whitespace for toString() is.
This solution does not seem to work in firefox, maybe it's a security feature for the browser? EDIT: Nevermind, it only does not work for Firefox Version 16.
Also beware of minifiers that strip comments... :D
This is why we can't have nice things.
You can do some weird stuff in javascript land. Though in all honesty, you should never use this.
P
Peter V. Mørch

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?


Anywhere you don't want to put your strings into seperate and distant script elements.
A valid objection! It isn't perfect. But for templates, that separation is not only ok, but perhaps even encouraged.
I prefer splitting everything over 80/120 characters into multiline, I'm afraid that's more than just templates. I now prefer 'line1 ' + 'line2' syntax. It's also the fastest (although this might rival it for really large texts). It's a nice trick though.
actually, this is HTML not Javascript :-/
however, the task of obtaining a multiline string in javascript can be done this way
X
XXN

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:

https://i.stack.imgur.com/vIVFc.png


Thanks for this! It's the only answer I've found that solves my problem, which involves unknown strings that may contain any combination of single and double quotes being directly inserted into the code with no opportunity for pre-encoding. (it's coming from a templating language that creates the JS -- still from a trusted source and not a form submission, so it's not TOTALLY demented).
This was the only method that actually worked for me to create a multi-line javascript string variable from a Java String.
What if the string is HTML?
$('#UniqueID').content()
@Pacerier Everything I've read, from Google as well as other sites, says that nowadays Google does index display:none content, most likely due to the popularity of JavaScript-styled front-ends. (For example, an FAQ page with hide/show functionality.) You need to be careful though, because Google says they can punish you if the hidden content appears to be designed to artificially inflate your SEO rankings.
V
Vignesh Subramanian

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>
  `

I think it's that you've just regurgitated what has already on the page for five years, but in a cleaner way.
won't slash concatenation also include the whitespace in beginning of lines?
j
jpfreire

Using script tags:

add a block containing your multiline text into head tag;

get your multiline text as is... (watch out for text encoding: UTF-8, ASCII)


I think this strategy is clean & far underused. jsrender uses this.
I'm using this with innerText iso innerHTML, But how do I make sure that the whitespaces are preserved ?
Also ajax queries in case you are using them. You can try to change your headers xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); I don't remember having other problems than mistyping comments in JS. Spaces where no problems.
s
semente

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)


I use this, except I put the '+' at the end of the preceding line, to make it clear the statement is continued on the next line. Your way does line up the indents more evenly though.
@Sean i use this too, and i still prefer put the '+' at the beginning of each new line added, and the final ';' on a new line, cuz i found it more 'correct'.
putting the + at the beginning allows one to comment out that line without having to edit other lines when its the first/last line of the sequence.
I prefer the + at the front too as visually I do not need to scan to the end of the line to know the next one is a continuation.
m
mplungjan

Downvoters: This code is supplied for information only.

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

DEMO

var new_comment; /*<< You: $text @ 2d ago EOF*/ // note the script tag here is hardcoded as the FIRST tag new_comment=document.currentScript.innerHTML.split("EOF")[1]; document.querySelector("ul").innerHTML=new_comment.replace('$text','This is a dynamically created text');


    That's horrific. +1. And you can use document.currentScript instead of getElement...
    Undefined "you" in chrome for osx
    jsfiddle-fixed - I must have had "you" defined globally in my console. Works now (chrome/osx). The nice thing about adding the comment to a var is that you're not in a function context, jsfiddle-function-heredoc although the function thing would be cool for class methods. might be better to pass it a replace { this: that } object anyways. fun to push something crazy to the limit anyway :)
    Forget the haters. This is the only correct answer bar ES6. All the other answers require concatenation, computation of some sort, or escaping. This is actually pretty cool and I'm going to use it as a way to add documentation to a game I'm working on as a hobby. As long as this trick isn't used for anything that could invoke a bug (I can see how someone would go "Semicolon, derp. Lets put the comment on the next line." and then it breaks your code.) But, is that really a big deal in my hobby game? No, and I can use the cool trick for something useful. Great answer.
    I've never been brave enough to use this technique in production code, but where I DO use it a lot is in unit testing, where often it's easiest to dump the value of some structure as a (quite long) string and compare it to what it 'should' be.
    m
    mightyiam

    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>
    */});
    

    This support in nodejs, using in browser must becareful.
    @HueiTan Docs state it also works in the browser. Which makes sense - it's just Function.prototype.String().
    ya but it said "While it does work fine in the browser, it's mainly intended for use in Node.js. Use at your own risk.While it does work fine in the browser, it's mainly intended for use in Node.js. Use at your own risk." (Just becareful XD)
    @HueiTanYep I read that part. But Function.prototype.toString() is pretty stable and well known.
    Best answer for me because it at least achieves multiline without all the rubbish in the middle(The rubbish at the beginning and ends I can deal with).
    N
    Niv

    Found a lot of over engineered answers here. The two best answers in my opinion were:

    1:

     let str = `Multiline string.
                foo.
                bar.`
    

    which eventually logs:

    Multiline string.
               foo.
               bar.  
    

    2:

    let str = `Multiline string.
    foo.
    bar.`
    

    That logs it correctly but it's ugly in the script file if str is nested inside functions / objects etc...:

    Multiline string.
    foo.
    bar.
    

    My really simple answer with regex which logs the str correctly:

    let str = `Multiline string.
               foo.
               bar.`.replace(/\n +/g, '\n');
    

    Please note that it is not the perfect solution but it works if you are sure that after the new line (\n) at least one space will come (+ means at least one occurrence). It also will work with * (zero or more).

    You can be more explicit and use {n,} which means at least n occurrences.


    Why wouldn't you just [ "line", "line2", "line3" ].join("\n").
    L
    Lonnie Best

    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.


    s
    stillatmycomputer

    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>
    

    Just think about it. Do you think it's valid? Don't you think it can cause display problems?
    Why the downvotes? This is a creative answer, if not very practical!
    no, it's not. One should rather use templates: $.tmpl() (api.jquery.com/tmpl), or EJS (embeddedjs.com/getting_started.html), etc. One reason for downvotes is that it's really far from a valid code and using this can cause huge display problems.
    I hope no one ever uses this answer in practice, but it's a neat idea
    Edge case when you have ' within the html. in that case you may have to use html entities &#39;.
    C
    Community

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

    this one didn't work: Creating multiline strings in JavaScript

    this worked fairly well, I have also figured out how to make it look good in Notepad++ source view: Creating multiline strings in JavaScript

    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.


    This is my first actual comment. I have gained the upvote privilege 2 days ago so so I immediately upvoted the one answer I mentioned above. Thank you to anyone who did upvote my feeble attempt to help.
    Thanks to everyone who actually upvoted this answer: I have now enough privileges to post normal comments! So thanks again.
    C
    Community

    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();
    

    m
    mikemaccana

    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.


    s
    seo

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

    https://i.stack.imgur.com/e51kg.png


    Wouldn't this add extraneous blank spaces?
    @tomByrer Yes, good observation. It's only good for strings which you don't care about white space, e.g. HTML.
    K
    Kamil Kiełczewski

    Exact

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

    text = `This Is A Multiline String ` // TEST console.log(JSON.stringify(text)); console.log(text);

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


    text is string why json.stringify?
    @FlatLander this is only for test - to see where are exactly new-line characters \n (to compare with ruby output (working example linked in answer) ) - this is improvement of Lonnie answer because new-line characters in his answer are not exactly the same positions as in ruby output
    a
    ankit bhusal

    A simple way to print multiline strings in JavaScript is by using template literals(template strings) denoted by backticks (` `). you can also use variables inside a template string-like (` name is ${value} `)

    You can also

    const value = `multiline` const text = `This is a ${value} string in js`; console.log(text);


    W
    Willem van der Veen

    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:

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

    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


    Is this now compatible with all recent browsers? Or are there some browsers which still do not support this syntax?
    Sorry for my extreme late comment, edited the answer added compatibility info ;)
    j
    jenil christo

    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


    This answer is not only small, incomplete and bad formatted, but also doesn't add absolutely anything to the previous answers. Flagging it and hopping to be deleted.
    S
    Stefan Steiger

    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


    Any documentation on the iPad/Safari limitation? MDN seems to think it's all good - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    @Campbeln: CoWorker told me this (he used the code). Haven't tested it myselfs. Might also depend on the iPad/Safari version - so probably depends.
    e
    earl3s

    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


    P
    Prakash GPz

    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";
    

    P
    Pragmatiq

    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";


    while i agree with your point, i wouldn't call javascript "good" ol
    How does this admonition stand up in 2022?
    P
    Pedro Andrade

    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'
    

    C
    Community

    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.