在 JavaScript 中创建多行字符串

Creating multiline strings in JavaScript

提问人:Newy 提问时间:4/30/2009 最后编辑:Ryan MNewy 更新时间:11/4/2022 访问量:2304591

问:

我在Ruby中有以下代码。我想将这段代码转换为 JavaScript。JS中的等效代码是什么?

text = <<"HERE"
This
Is
A
Multiline
String
HERE
javascript 字符串 heredoc

评论


答:

223赞 5 revs, 2 users 97%alex #1

你可以这样做...

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

评论

0赞 Matt K 11/4/2011
第一个例子很棒,很简单。比 \ 方法好得多,因为我不确定浏览器将如何处理反斜杠作为转义字符和多行字符。
0赞 Brock Adams 11/22/2012
CDATA代码(E4X)已经过时,即使在Firefox中也将很快停止工作
0赞 Paul Sweatte 1/19/2013
e4x.js 将是面向未来的良好解决方案
4435赞 Anonymous 4/30/2009 #2

更新:

ECMAScript 6 (ES6) 引入了一种新型的文字,即模板文字。它们具有许多特征,可变插值等,但最重要的是,对于这个问题,它们可以是多行的。

模板文本由反引号分隔:

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

(注意:我不提倡在字符串中使用 HTML)

浏览器支持是可以的,但你可以使用转译器来更兼容。


原 ES5 答案:

Javascript 没有 here-document 语法。但是,您可以转义文字换行符,它接近:

"foo \
bar"

评论

281赞 staticsan 4/30/2009
请注意:有些浏览器会在继续时插入换行符,有些则不会。
45赞 jcollum 4/18/2011
Visual Studio 2010 似乎也对这种语法感到困惑。
63赞 some 9/25/2012
@Nate 它在 ECMA-262 第 5 版第 7.8.4 节中指定,称为 LineContinuation:“行终止符不能出现在字符串文字中,除非作为 LineContinuation 的一部分以生成空字符序列。使行终止符成为字符串文本的 String 值的一部分的正确方法是使用转义序列,例如 \n 或 \u000A。
23赞 SamStephens 3/21/2013
我不明白为什么当浏览器不一致地对待它时你会这样做。多行的“line1\n” + “line2” 具有足够的可读性,并且保证您的行为一致。
23赞 Tom Andraszek 5/25/2017
“浏览器支持正常”...IE11 不支持 - 不正常
738赞 KooiInc 4/30/2009 #3

该模式在 js 中不可用(我记得在我过去的 Perl 时代经常使用它)。text = <<"HERE" This Is A Multiline String HERE

为了保持对复杂或长多行字符串的监督,我有时会使用数组模式:

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

或者 Anonymous 已经显示的模式(转义换行符),这可能是代码中一个丑陋的块:

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

这是另一个奇怪但有效的“技巧”1

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

外部编辑:JSFiddle

ES20xx 支持使用模板字符串跨越多行字符串

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 注意:在缩小/混淆代码后,这将丢失

评论

39赞 BMiner 7/17/2011
请不要使用数组模式。在大多数情况下,它比普通字符串连接慢。
86赞 Benjamin Atkin 8/20/2011
阵列模式的可读性更强,应用程序的性能损失通常可以忽略不计。正如性能测试所显示的那样,即使是 IE7 每秒也可以执行数万次操作。
23赞 Pavel 5/21/2012
+1 表示一种优雅的替代方案,它不仅在所有浏览器中都以相同的方式工作,而且面向未来。
28赞 Ruan Mendes 8/4/2013
@KooiInc 测试从已创建的数组开始,这会使结果出现偏差。如果添加数组的初始化,则直接串联速度更快 jsperf.com/string-concat-without-sringbuilder/7 请参阅 stackoverflow.com/questions/51185/...作为换行符的技巧,它可能没问题,但它肯定做了比它应该做的更多的工作
12赞 3/25/2014
@BMiner:1)“过早优化是万恶之源”——Donald Knuth,2)“可读性”在旁观者的眼中
11赞 stillatmycomputer 11/24/2010 #4

这适用于 IE、Safari、Chrome 和 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>

评论

8赞 Sk8erPeter 2/24/2012
想想看。你认为它有效吗?你不认为它会导致显示问题吗?
6赞 dotancohen 2/29/2012
为什么投反对票?这是一个创造性的答案,如果不是很实用的话!
3赞 Sk8erPeter 3/24/2012
不,不是。应该使用模板:$.tmpl() (api.jquery.com/tmpl) 或 EJS (embeddedjs.com/getting_started.html) 等。投反对票的一个原因是它离有效代码很远,使用它可能会导致巨大的显示问题。
0赞 DCShannon 3/14/2015
我希望没有人在实践中使用这个答案,但这是一个巧妙的想法
0赞 borracciaBlu 12/18/2020
当你在html中时,边缘情况。在这种情况下,您可能必须使用 HTML 实体 。'&#39;
371赞 Jordão 4/7/2011 #5

您可以在纯 JavaScript 中使用多行字符串。

此方法基于函数的序列化,该序列化被定义为与实现相关。它确实适用于大多数浏览器(见下文),但不能保证它将来仍然有效,所以不要依赖它。

使用以下函数:

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

你可以有这样的 here-documents:

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

评论

284赞 fforw 6/17/2011
What!? creating and decompiling a Function to hack a multiline comment into being a multiline string? Now that's ugly.
5赞 Jason Kleban 9/10/2011
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.
3赞 Jordão 9/10/2011
@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.
2赞 Lodewijk 1/9/2012
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.)
3赞 Jason 7/13/2012
Extremely handy. I'm using it for (Jasmine) unit tests, but avoiding it for production code.
11赞 Tyler 5/20/2011 #6

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.

评论

0赞 Tyler 7/24/2011
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.
0赞 Tyler 8/31/2012
Thanks to everyone who actually upvoted this answer: I have now enough privileges to post normal comments! So thanks again.
1540赞 Devin Rhode 6/6/2011 #7

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

评论

28赞 Matt Browne 2/27/2013
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).
8赞 EricP 5/24/2014
Note that template strings aren't supported in IE11, Firefox 31, Chrome 35, or Safari 7. See kangax.github.io/compat-table/es6
46赞 ShreevatsaR 8/1/2016
@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.\
3赞 Tiago Duarte 11/11/2016
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
3赞 Michael Fever 6/27/2019
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!
25赞 semente 12/14/2011 #8

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)

评论

3赞 Sean 10/4/2012
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.
0赞 AgelessEssence 11/14/2013
@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'.
7赞 moliad 12/12/2013
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.
3赞 Daniel Sokolowski 5/7/2014
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.
94赞 Peter V. Mørch 1/4/2012 #9

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?

评论

25赞 Lodewijk 1/9/2012
Anywhere you don't want to put your strings into seperate and distant script elements.
10赞 Peter V. Mørch 2/3/2012
A valid objection! It isn't perfect. But for templates, that separation is not only ok, but perhaps even encouraged.
2赞 Lodewijk 2/4/2012
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.
29赞 CpILL 5/22/2012
actually, this is HTML not Javascript :-/
6赞 Davi Fiamenghi 7/31/2013
however, the task of obtaining a multiline string in javascript can be done this way
60赞 Tom Beech 8/17/2012 #10

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

评论

4赞 octern 6/24/2013
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).
0赞 beginner_ 8/6/2013
This was the only method that actually worked for me to create a multi-line javascript string variable from a Java String.
4赞 Dan Dascalescu 1/24/2014
What if the string is HTML?
4赞 mplungjan 1/24/2014
$('#UniqueID').content()
1赞 Gavin 8/8/2017
@Pacerier Everything I've read, from Google as well as other sites, says that nowadays Google does index 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.display:none
33赞 jpfreire 8/24/2012 #11

Using script tags:

  • add a block containing your multiline text into tag;<script>...</script>head
  • 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>
    

评论

0赞 xdhmoore 1/9/2015
I think this strategy is clean & far underused. jsrender uses this.
0赞 David Nouls 7/16/2015
I'm using this with innerText iso innerHTML, But how do I make sure that the whitespaces are preserved ?
0赞 jpfreire 10/28/2015
Also ajax queries in case you are using them. You can try to change your headers I don't remember having other problems than mistyping comments in JS. Spaces where no problems.xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
0赞 Anmol Saraf 11/23/2012 #12

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

评论

7赞 Sejanus 12/14/2012
well obviously if you have a space after a backslash, backslash escapes the space. It is supposed to escape linebreak, not space.
1赞 Aditya Hajare 1/28/2013 #13

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

评论

0赞 Bergi 1/28/2013
<xmp> is so deprecated. It may be allowed in HTML, but should not be used by any authors. See stackoverflow.com/questions/8307846/…
0赞 Aditya Hajare 1/28/2013
@Bergi, you are right.. and using with escapes wont help in my solution.. I came across similar issue today and trying to figure out a workaround.. but in my case, I found one very n00bish way to fix this issue by putting output in html comments instead of <xmp> or any other tag. lol. I know its not a standard way to do this but I will work on this issue more tomorrow mornin.. Cheers!!<pre>;
0赞 Jesse Glick 12/10/2013
Unfortunately even with Chrome tries to load any images mentioned in the example block.style="display:none"<img>
21赞 mplungjan 2/17/2013 #14

Downvoters: This code is supplied for information only.

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

DEMO

var new_comment; /*<<<EOF 
    <li class="photobooth-comment">
       <span class="username">
          <a href="#">You</a>:
       </span>
       <span class="comment-text">
          $text
       </span> 
       @<span class="comment-time">
          2d
       </span> ago
    </li>
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');
<ul></ul>

评论

17赞 Orwellophile 5/27/2015
That's horrific. +1. And you can use document.currentScript instead of getElement...
1赞 mplungjan 5/28/2015
Undefined "you" in chrome for osx
1赞 Orwellophile 6/2/2015
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 :)
1赞 Thomas Dignan 7/28/2015
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.
2赞 Ben McIntyre 2/3/2016
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.
-14赞 BearCode #15

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

评论

16赞 Colin 2/27/2013
You should use instead. MUCH cleaner.var myString += "Second line \n";
13赞 Michael Mior 7/11/2013
Actually, you should use The shouldn't be repeated.myString += "Second line \n";var
1赞 e-info128 8/2/2013
use + only for concatenate strings. Not need declare all buffer for each line. Its horrorific.
1赞 BearCode 11/26/2014
Should I correct my answer or should I leave it there as a good example of how NOT to do things? If it's best for the people who learn JavaScript, I don't mind leaving it there as it is now. A few negative points can't hurt that much.
0赞 Iain MacKay 3/7/2013 #16

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.

评论

1赞 Jan 9/13/2015
this works: function s() { return Array.prototype.join.call(arguments, '\n'); }
186赞 Luke 3/22/2013 #17

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)

评论

50赞 Kevin Cox 4/8/2013
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 is.toString()
2赞 Bill Software Engineer 6/7/2013
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.
59赞 jondavidjohn 10/23/2013
Also beware of minifiers that strip comments... :D
9赞 Danilo M. Oliveira 10/16/2018
This is why we can't have nice things.
8赞 Luke 10/26/2018
You can do some weird stuff in javascript land. Though in all honesty, you should never use this.
0赞 e-info128 8/3/2013 #18

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

评论

5赞 Barry Chapman 2/19/2014
that is horrendous, theres a reason people do NOT program that way
7赞 Tek 3/11/2014
Keep HTML where it should be. In the HTML document. Hide the HTML and use jQuery to show it when it's needed. Much cleaner and much more maintainable.
0赞 e-info128 6/16/2020
Yes, I want to apologize, 7 years have passed and I no longer program that way, clearly the html code must be in html or jsx and not inside javascript code.
0赞 AdrianCooney 8/28/2013 #19

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

3赞 KTys 10/14/2013 #20

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.

-3赞 AgelessEssence 11/14/2013 #21

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.

评论

1赞 Orwellophile 5/27/2015
I confess I have done this a number of times to get complex quoted strings into javascript, although I pre-prepare them. But you're wrong about not being able to use javascript variables, you could implement coffee-script style interpolations which look like #{this.example}, and replace using a .replace regex with a closure function.
10赞 pocheptsov 12/12/2013 #22

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

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();
3赞 Mr. Alien 1/18/2014 #23

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);
9赞 mikemaccana 2/10/2014 #24

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.

19赞 Shahar 'Dawn' Or 4/25/2014 #25

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

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

评论

1赞 Huei Tan 5/5/2014
在浏览器中使用时必须小心。nodejs
3赞 mikemaccana 7/14/2014
@HueiTan Docs 声明它也可以在浏览器中使用。这是有道理的 - 它只是.Function.prototype.String()
0赞 Huei Tan 7/14/2014
是的,但它说:“虽然它在浏览器中工作正常,但它主要用于 Node.js。使用风险自负。虽然它在浏览器中工作正常,但它主要用于 Node.js。使用风险自负。(小心XD)
0赞 mikemaccana 7/14/2014
@HueiTanYep我读了那部分。 但是 Function.prototype.toString() 非常稳定且广为人知。
1赞 Damien Golding 8/27/2014
对我来说最好的答案是因为它至少实现了多行,中间没有所有的垃圾(我可以处理开头和结尾的垃圾)。
34赞 Vignesh Subramanian 5/26/2014 #26

有多种方法可以实现此目的

1. 斜杠串联

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

2. 规则串联

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

3. 数组连接串联

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

性能方面,斜杠串联(第一个)是最快的。

有关性能的更多详细信息,请参阅此测试用例

更新:

ES2015 中,我们可以利用其模板字符串功能。有了它,我们只需要使用反引号来创建多行字符串

例:

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

评论

11赞 RandomInsano 8/3/2014
我认为是你刚刚反刍了五年来已经在页面上的内容,但以一种更干净的方式。
0赞 f.khantsis 5/10/2017
斜杠连接是否也包括行首的空格?
0赞 Charles Brandt 9/9/2014 #27

如果你碰巧只在 Node 中运行,你可以使用 fs 模块从文件中读入多行字符串:

var diagram;
var fs = require('fs');
fs.readFile( __dirname + '/diagram.txt', function (err, data) {
  if (err) {
    throw err; 
  }
  diagram = data.toString();
});
9赞 seo 4/29/2015 #28

如果您愿意使用转义换行符,则可以很好地使用它们。它看起来像一个带有页面边框的文档

在此处输入图像描述

评论

3赞 tomByrer 12/6/2015
这不会增加多余的空格吗?
1赞 seo 12/7/2015
@tomByrer 是的,很好的观察。它只适用于你不关心空格的字符串,例如 .HTML。
7赞 Stefan Steiger 9/21/2015 #29

你可以使用 TypeScript (JavaScript SuperSet),它支持多行字符串,并且可以无开销地转译回纯 JavaScript

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

alert(templates.myString);

如果你想用纯 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)

请注意,iPad/Safari 不支持'functionName.toString()'

如果你有很多遗留代码,你也可以在 TypeScript 中使用纯 JavaScript 变体(用于清理目的):

interface externTemplates
{
    myString:string;
}

declare var templates:externTemplates;

alert(templates.myString)

您可以使用纯 JavaScript 变体中的多行字符串对象,将模板放入另一个文件(您可以将其合并到捆绑包中)。

您可以在 http://www.typescriptlang.org/Playground 试用
TypeScript

评论

0赞 Campbeln 8/6/2017
有关于iPad / Safari限制的文档吗?MDN 似乎认为一切都很好——developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/......
0赞 Stefan Steiger 8/7/2017
@Campbeln:CoWorker 告诉我这个(他使用了代码)。我自己没有测试过。可能还取决于 iPad/Safari 版本 - 所以可能取决于。
12赞 Lonnie Best 11/4/2015 #30

javascript 中的等价物是:

var text = `
This
Is
A
Multiline
String
`;

这是规范。请参阅本底部的浏览器支持。这里也有一些例子

6赞 earl3s 3/29/2016 #31

ES6 允许您使用反引号在多行上指定字符串。它称为模板文本。喜欢这个:

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

使用反引号适用于 NodeJS,Chrome、Firefox、Edge、Safari 和 Opera 都支持它。

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

4赞 Prakash GPz 7/14/2016 #32

还要注意的是,当在每行末尾使用正反斜杠将字符串扩展到多行时,正反斜杠后的任何额外字符(主要是空格、制表符和错误添加的注释)都会导致意外的字符错误,我花了一个小时才发现

var string = "line1\  // comment, space or tabs here raise error
line2";
2赞 Sonevol 8/14/2017 #33

您必须使用串联运算符“+”。

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

通过使用您的源代码将如下所示 -\n

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

通过使用浏览器,输出将如下所示 -<br>

This
is
multiline
string.
4赞 Pragmatiq 10/12/2017 #34

出于对互联网的热爱,请使用字符串连接,并选择不使用 ES6 解决方案。ES6 并非全面支持,就像 CSS3 和某些浏览器适应 CSS3 运动的速度很慢一样。使用普通的 JavaScript,您的最终用户会感谢您。

例:

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

评论

3赞 user151496 3/5/2018
虽然我同意你的观点,但我不会称 JavaScript 为“好”OL
1赞 Ken Ingram 3/15/2022
这个告诫在2022年如何站得住脚?
0赞 user3221512 12/7/2022
最终用户有责任保持浏览器更新。开发人员有责任以正确的方式编写代码并使产品更好。
8赞 jenil christo 7/14/2018 #35

ES6 的方法是使用模板文字:

const str = `This 

is 

a

multiline text`; 

console.log(str);

更多参考资料在这里

评论

0赞 Victor Schröder 1/19/2019
这个答案不仅小、不完整且格式错误,而且对之前的答案也没有绝对增加任何内容。标记它并跳转到删除。
8赞 Willem van der Veen 9/9/2018 #36

在 Javascrips 中制作多行字符串的最简单方法是使用反引号 ( '' )。这允许您创建多行字符串,您可以在其中插入带有 .${variableName}

例:

let name = 'Willem'; 
let age = 26;

let multilineString = `
my name is: ${name}

my age is: ${age}
`;

console.log(multilineString);

兼容性:

  • 它被介绍在ES6//es2015
  • 现在,所有主要浏览器供应商(Internet Explorer 除外)都原生支持它

在此处检查Mozilla文档中的确切兼容性

评论

0赞 cmpreshn 9/28/2018
现在是否与所有最近的浏览器兼容?或者是否有一些浏览器仍然不支持此语法?
0赞 Willem van der Veen 10/2/2018
对不起,我的评论太晚了,编辑了答案,添加了兼容性信息;)
0赞 Sapphire_Brick 7/25/2019 #37

规则是:在字符串内时,在需要换行符的任何位置使用 \n;你不必在\n之前或之后加一个空格,JavaScript的解释器足够聪明,知道不可打印的字符表示有多长。

11赞 Kamil Kiełczewski 6/11/2020 #38

确切

Ruby 产生: - 下面的 JS 产生完全相同的字符串"This\nIs\nA\nMultiline\nString\n"

text = `This
Is
A
Multiline
String
`

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

这是对 Lonnie Best 答案的改进,因为他的答案中的换行符与 ruby 输出中的位置并不完全相同

评论

0赞 FlatLander 7/12/2020
text is string 为什么是 json.stringify?
1赞 Kamil Kiełczewski 7/13/2020
@FlatLander这只是为了测试 - 看看换行符的确切位置(与 ruby 输出进行比较(答案中链接的工作示例)) - 这是对 Lonnie 答案的改进,因为他的答案中的换行符与 ruby 输出中的位置不完全相同\n
5赞 Pedro Andrade 7/9/2020 #39

您可以使用标记模板来确保获得所需的输出。

例如:

// 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'
2赞 NimaDoustdar 10/23/2021 #40

JavaScript 从来没有一个真正好的方法来处理多行字符串,直到 2015 年引入了 ES6 以及模板文字。

模板文字是由反引号('')分隔的字符串,而不是普通的single('')/doublebl(“”)e引号分隔符。

评论

0赞 Hasan Shouman 11/5/2022
我不知道为什么这没有被选为正确答案!
18赞 Niv 11/6/2021 #41

在这里找到了很多过度设计的答案。 在我看来,最好的两个答案是:

1:

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

最终记录:

Multiline string.
           foo.
           bar.  

2:

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

这正确地记录了它,但如果 str 嵌套在函数/对象等中,它在脚本文件中是丑陋的......

Multiline string.
foo.
bar.

我对正则表达式的非常简单的答案,它正确记录了 str:

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

请注意,这不是完美的解决方案,但如果您确定在新行 (\n) 之后至少会出现一个空格(+ 表示至少出现一次),它就会起作用。它也可以与 *(零或更多)一起使用。

您可以更明确地使用 {n,},这意味着至少出现 n 次。

评论

6赞 Kaz 1/22/2022
你为什么不只是.[ "line", "line2", "line3" ].join("\n")
4赞 Abhishek Goel 1/20/2022 #42

带变量的多行字符串

var x = 1
string = string + `<label class="container">
                       <p>${x}</p>
                   </label>`;
30赞 itsankitbhusal 3/3/2022 #43

在 JavaScript 中打印多行字符串的一种简单方法是使用由反引号 (' ') 表示的模板文字(模板字符串)。您还可以在模板中使用类似字符串的变量('name is ${value} `)

您还可以

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