Creating multiline strings in JavaScript

2018-12-30 23:10发布

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

30条回答
十年一品温如言
2楼-- · 2018-12-30 23:40

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

查看更多
伤终究还是伤i
3楼-- · 2018-12-30 23:41

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.';
查看更多
妖精总统
4楼-- · 2018-12-30 23:41

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?

查看更多
怪性笑人.
5楼-- · 2018-12-30 23:41

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.

查看更多
柔情千种
6楼-- · 2018-12-30 23:42

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.

查看更多
几人难应
7楼-- · 2018-12-30 23:42

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();
查看更多
登录 后发表回答