在 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

转载于:https://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript

weixin_41568208
北城已荒凉 Check this out on different ways to achieve the same. I have added performance of each method too stackoverflow.com/a/23867090/848841
6 年多之前 回复
weixin_41568110
七度&光 See stackoverflow.com/a/6247331/632951
6 年多之前 回复

30个回答

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"
csdnceshi56
lrony* Added bonus.. you don't need to escape quotes, so stringified json looks reasonable: let z = {"p1" : "1", "p2" : "2"}
大约 2 年之前 回复
weixin_41568126
乱世@小熊 It Fails for IE
接近 3 年之前 回复
csdnceshi76
斗士狗 Browser support is NOT ok actually. IE gives "Invalid character" error for that character. I don't understand how it got so many upvotes...
接近 3 年之前 回复
csdnceshi57
perhaps? I have tested template literal on safari 7.1 Mavericks, I doesn't work.
大约 3 年之前 回复
weixin_41568174
from.. What about concatenation within the multiline string?
3 年多之前 回复
weixin_41568183
零零乙 "Browser support is OK"... not supported by IE11 - not OK
3 年多之前 回复
csdnceshi78
程序go Thank you so much to the person who provided this answer.
3 年多之前 回复
csdnceshi73
喵-见缝插针 and how to add vars to this strings?
接近 4 年之前 回复
csdnceshi65
larry*wei AFAIK, IE still does not support it
大约 4 年之前 回复
csdnceshi62
csdnceshi62 The template strings are very useful. Too bad that a lot of IDE's (including NetBeans) still do not support it.
接近 5 年之前 回复
csdnceshi68
local-host I actually use concatenation far more often, but it depends on the use case. At the moment I'm creating some "plug-in" type js files. It's convenient in this case to just copy and paste the css and html markup I need wholesale into a JS string. I understand future versions of HTML will allow the <link> tag to allow embedding "html" files, but a JS string is the easiest way atm to include JS/CSS/HTML
5 年多之前 回复
csdnceshi63
elliott.david Good idea to point to the good solutions. This backtick thing is neat, however I often prefer string concatenation - often makes it more readable. Or maybe a matter of taste.
5 年多之前 回复
csdnceshi68
local-host +1. Buried deep within all the text on this page is a mention of the "backtick character" which in Chrome and FFox does exactly what the OP requested. Using backticks won't suffice for the majority since it won't work in Safari, etc, but it would be nice if it figured more prominently in the discussion
5 年多之前 回复
csdnceshi63
elliott.david This solution is not wrong - but it's obviously not the best. So sad it has such a high count here. Scroll down to read better solutions.
接近 6 年之前 回复
weixin_41568110
七度&光 And I haven't tried to answer the question because there was already plenty of other answers. Dresende has already commented "This is wrong, it's not multiline. It's only 1 line.", so I didn't need to repeat it. I only provided information about the LineContinuation in a comment, so I was a little surprised when you wrote your comment to me instead of Anonymous who was the one who answered the question! :) There is no support in ECMAScript 5.1 or earlier for the requested syntax. The closest thing is an escaped new line followed by a LineContinuation, but it is ugly, in my opinion.
大约 6 年之前 回复
csdnceshi59
ℙℕℤℝ My point is that the question is asking for a multiline string, so this doesn't answer the question. Maybe the confusion is just because of the deleted comment that I never saw
大约 6 年之前 回复
weixin_41568110
七度&光 Yes? That is what the first sentence of the quote I did from the standard says. So what is your point? The seconds sentence tells in a formal way how to produce a string that has line terminators and that is split into multiple lines in the source code. I don't remember what Nate wrote in the now deleted comment, but I think it was something about this not being part of javascript. I refereed to the standard where it is defined and quoted the relevant part.
大约 6 年之前 回复
csdnceshi59
ℙℕℤℝ It's not a multiline string, it's a one line string split over multiple lines of code that make up a single statement
大约 6 年之前 回复
csdnceshi60
℡Wang Yan This syntax is perfect for machines who will never accidentally put a space between the backslash and the newline. Everyone else will have to paste their code into SO's comment editor, to see the highlighted difference between \ and \
大约 7 年之前 回复
csdnceshi66
必承其重 | 欲带皇冠 node 0.10.0: works; requires explicit \n chars. to insert actual line breaks (per ECMAScript 5 spec). In other words: if you want every string-literal source-code line to correspond to a line in the resulting string, end lines with \n\
7 年多之前 回复
csdnceshi55
~Onlooker 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.
7 年多之前 回复
csdnceshi53
Lotus@ 'line1' + '\n' ...what is wrong with this?
7 年多之前 回复
csdnceshi75
衫裤跑路 Also: If you use UglifyJS for minification, it will put multiline strings created this way onto a single line (newline characters will not be added at the continuance). So as long as the browser you're developing in behaves the same way, then you can use this approach and get consistent results across browsers in the production version of your app (i.e. after minification).
7 年多之前 回复
csdnceshi75
衫裤跑路 So in summary it seems this is the most straightforward approach, compatible with all browsers at least back to IE6 (and probably earlier), as long as you don't care whether or not extra newlines might be added at the end of each line. Does anyone know which browsers/versions add newlines and which don't?
7 年多之前 回复
weixin_41568110
七度&光 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."
大约 8 年之前 回复
csdnceshi50
三生石@ Visual Studio 2010 seems to be confused by this syntax as well.
9 年多之前 回复
csdnceshi80
胖鸭 Be warned: some browsers will insert newlines at the continuance, some will not.
11 年多之前 回复

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.';
csdnceshi66
必承其重 | 欲带皇冠 Lets just say I query a web service which gives out data to render in an HTML page,I write JS variables to store HTML & pass values in it. like data +=' <span class="'+data['class']++'">'+data['name']+'</span>.Would this be a bad approach?
2 年多之前 回复
csdnceshi58
Didn"t forge 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
接近 4 年之前 回复
csdnceshi65
larry*wei 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.
大约 4 年之前 回复
csdnceshi56
lrony* In EcmaScript 6, you'll be able to use backticks for Template Strings, known in the spec as a NoSubstitutionTemplate. I think you can try this and other features by first downloading canary chrome and then turning on Enable Experimental JavaScript. This doesn't work for me in canary chrome for windows even after enabling Experimental JavaScript. Agreed. I had tried it while writing a Chrome userscript and it didn’t work in any new or old version of Chromium or Chrome that I tried; they all threw ILLEGAL TOKEN errors. I guess as usual, Google wants to insist people do things their way.
6 年多之前 回复
csdnceshi78
程序go Note that template strings aren't supported in IE11, Firefox 31, Chrome 35, or Safari 7. See kangax.github.io/compat-table/es6
6 年多之前 回复
weixin_41568174
from.. This no longer works in Chrome Canary.
6 年多之前 回复
csdnceshi69
YaoRaoLov Those who want to try these stuffs, be sure to check [Chrome Canary][1] [1]: google.com/intl/en/chrome/browser/canary.html
接近 7 年之前 回复
csdnceshi72
谁还没个明天 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).
7 年多之前 回复
csdnceshi74
7*4 this doesn't work for me in canary chrome for windows even after enabling Experimental JavaScript
接近 8 年之前 回复

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)
weixin_41568131
10.24 You can do some weird stuff in javascript land. Though in all honesty, you should never use this.
接近 2 年之前 回复
csdnceshi71
Memor.の This is why we can't have nice things.
大约 2 年之前 回复
weixin_41568196
撒拉嘿哟木头 Just copy-paste the code from the answer up to .toString() in your browser console and see what it returns.
大约 4 年之前 回复
csdnceshi51
旧行李 Why are 14 and -3 the parameters passed to slice?
4 年多之前 回复
csdnceshi57
perhaps? Thats true. Since I'm using coffeescript, it ends up in a combination: ###).toString().slice(13,-1).trim().slice(2,-2)
大约 6 年之前 回复
csdnceshi68
local-host That will only handle the whitespace before and after, It won't handle things like function ( ) { .... But it may be sufficient.
大约 6 年之前 回复
csdnceshi57
perhaps? you could use trim().
大约 6 年之前 回复
csdnceshi55
~Onlooker Also beware of minifiers that strip comments... :D
大约 7 年之前 回复
csdnceshi53
Lotus@ 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.
7 年多之前 回复
csdnceshi62
csdnceshi62 stackoverflow.com/a/5571069/499214
7 年多之前 回复
csdnceshi68
local-host 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.
7 年多之前 回复

You can do this...

var string = 'This is\n' +
'a multiline\n' + 
'string';
csdnceshi52
妄徒之命 e4x.js would be the good future-proof solution
接近 8 年之前 回复
weixin_41568134
MAO-EYE The CDATA code (E4X) is obsolete and will soon stop working even in Firefox.
接近 8 年之前 回复
csdnceshi78
程序go 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.
接近 9 年之前 回复

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

csdnceshi75
衫裤跑路 I like the array approach. Sure, it may be slower, but correctness and readability is, typically, more important. I could see a rationale to not use it on the browser, but it would be a good approach with server-side javascript. Plus, now we have backtick ("`") string templates that are even better.
大约 2 年之前 回复
csdnceshi63
elliott.david Oh I get my confusion there. The ECMAScript versions started beeing named "ES20XX" after ES6, I forgot about that.
大约 2 年之前 回复
csdnceshi62
csdnceshi62 see exploringjs.com/es6/ch_template-literals.html, also exploringjs.com/es6/ch_faq.html#sec_es6-vs-es2015
大约 2 年之前 回复
csdnceshi63
elliott.david AFAIK, Template strings (or template literals) were not supported until ES2015 (ES6), so saying that any ES20XX version do seems wrong.
大约 2 年之前 回复
csdnceshi62
csdnceshi62 why not? The sub header was not informative.
大约 2 年之前 回复
csdnceshi63
elliott.david Why this edit ?
大约 2 年之前 回复
csdnceshi70
笑故挽风 What about concatenation within the multiline string?
3 年多之前 回复
csdnceshi62
csdnceshi62 not anymore. This is a very old issue (2009), browsers are much better nowadays
3 年多之前 回复
csdnceshi65
larry*wei Why would string concatenation be much faster than join? Is there some sort of magic in join's implementation?
3 年多之前 回复
csdnceshi79
python小菜 There are >150 versions of the jsPerf test. I did not check even a large number of them. Version 25 tests both string concatenation and .join() on both predefined and inline arrays. String concatenation is on the order of 500 to 1,000 times faster than Array's .join(), based on testing in the current versions of Chrome and Firefox on 2017-02-19. String concatenation can be written with a similar level of readability. In my opinion, there is no effective benefit of using .join() for this, and a significant cost for just a "cool" style choice.
3 年多之前 回复
csdnceshi68
local-host Unless this is deep inside a million nested loops and running on a potato, efficiency is probably irrelevant next to readability. +1 for the array
接近 5 年之前 回复
weixin_41568126
乱世@小熊 Tested on Win 8.1 in Chrome and Firefox, join is 99% slower for me. (1,997,886,948 vs 18,679,979 respectively 2,161,096,056 vs 2,145,283)
5 年多之前 回复
weixin_41568134
MAO-EYE Tested on Win 8.1 in Firefox & Chrome, join is 33% slower than concatenate.
5 年多之前 回复
csdnceshi58
Didn"t forge +1 for the amazing regexp trick. Works like a charm and I love it. I still am having an issue with escaping /* characters within xml strings, but its unnecessary. I'm only doing this for file based testing. Thanks man!
5 年多之前 回复
csdnceshi50
三生石@ Be careful with the "comment in function" solution. Keep in mind that as soon as you will want to minimize your JS code, your comments will be stripped off.
接近 6 年之前 回复
csdnceshi77
狐狸.fox When tested on Mac 10.9 with Firefox 32, the join was "100%" slower than concatenation, according to jsperf (972 million vs 1 million ops/second).
大约 6 年之前 回复
csdnceshi69
YaoRaoLov 1) "Premature optimization is the root of all evil" - Donald Knuth, and 2) 'readability' is in the eye of the beholder
6 年多之前 回复
csdnceshi73
喵-见缝插针 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
大约 7 年之前 回复
csdnceshi53
Lotus@ I personally just concatenate strings and let the performance issues get sorted out when the JS is minified and the strings are combined.
7 年多之前 回复
csdnceshi78
程序go Must encase with 'singles' and NOT "doubles" for me in Notepad++
接近 8 年之前 回复
csdnceshi64
游.程 +1 for an elegant alternative that not only works the same way in all browsers, but is also future-proof.
8 年多之前 回复
csdnceshi72
谁还没个明天 I like joins. Write the code that writes the code. Much better than concatenating many times. It's redundancy.
8 年多之前 回复
csdnceshi55
~Onlooker That's actually quite a bunch slower than those join's. Plus the join's are kind of the preferable way to do it. Joins it is.
接近 9 年之前 回复
csdnceshi55
~Onlooker You could make a little function to do fast joins: function fastjoin(array){ out = ''; for(i in array){ out += i; } return out; }
接近 9 年之前 回复
weixin_41568196
撒拉嘿哟木头 This is my favorite way (it looks nice), and fast enough that I am willing to take a minor speed hit for code readability.
接近 9 年之前 回复
csdnceshi62
csdnceshi62 feel free to cook up a jsperf.com-test yourself, or fiddle around with my test ;)
大约 9 年之前 回复
csdnceshi52
妄徒之命 some browsers can compile several literal concats into a single literal string, and in machine code, no less. The benchmark ought to have tried a large concat of string variables as well, which would be a more fair comparison against join().
大约 9 年之前 回复
csdnceshi57
perhaps? 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.
大约 9 年之前 回复
csdnceshi80
胖鸭 in most cases... did you also include the time required to allocate/build the array? Regardless... it's a bit more readable than joining arrays.
9 年多之前 回复
csdnceshi62
csdnceshi62 Really? jsperf.com/join-concat/24
9 年多之前 回复
csdnceshi80
胖鸭 Please don't use the array pattern. It will be slower than plain-old string concatenation in most cases.
9 年多之前 回复

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.

csdnceshi75
衫裤跑路 I know, just making the answer a bit more complete for new people finding it. ;)
大约 3 年之前 回复
weixin_41568183
零零乙 indeed you don't. In fact, you don't even should use this solution in the first place
大约 3 年之前 回复
csdnceshi75
衫裤跑路 You don't need regex for this: function hereDoc(f) { var fs = ''+f; return fs.substring(fs.indexOf("/*!")+3, fs.lastIndexOf("*/")); }
大约 3 年之前 回复
weixin_41568134
MAO-EYE It's pretty neat actually, if only its implementation independent.
3 年多之前 回复
csdnceshi77
狐狸.fox Even simpler hereDoc(() => {/*! Theirs not to make reply, Theirs not to reason why, Theirs but to do and die */});
接近 4 年之前 回复
csdnceshi80
胖鸭 Syntax become ugly when you need to pass variables inside long multi-line text. Or you have to replace strings several times.
接近 5 年之前 回复
csdnceshi60
℡Wang Yan Its was failed when I have </script> literal inside the comments.
6 年多之前 回复
weixin_41568126
乱世@小熊 You just made it easy for me to add huge html blocks to my QUnit tests! I am now creating a StaticStrings object in my test class that holds a bunch of these strings.
6 年多之前 回复
csdnceshi50
三生石@ Elegant, yet it does not work in Rhino.
接近 7 年之前 回复
csdnceshi70
笑故挽风 My Heredoc works in my Fx and Chrome on Mac: DEMO
7 年多之前 回复
weixin_41568183
零零乙 I don't know if that's a good idea, even for testing. Your test environment might also evolve and drop this accidental feature. Please reconsider. This post is for entertainment purposes only....
8 年多之前 回复
csdnceshi61
derek5. Extremely handy. I'm using it for (Jasmine) unit tests, but avoiding it for production code.
8 年多之前 回复
csdnceshi68
local-host 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.)
接近 9 年之前 回复
weixin_41568183
零零乙 thanks for the information; this is exactly why this approach is an unreliable hack.
接近 9 年之前 回复
weixin_41568183
零零乙 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.
大约 9 年之前 回复
csdnceshi67
bug^君 I had hope for function.toSource() for FF but no.
大约 9 年之前 回复
csdnceshi67
bug^君 jsfiddle.net/vGdez works only in FF
大约 9 年之前 回复
csdnceshi67
bug^君 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.
大约 9 年之前 回复
weixin_41568183
零零乙 It's actually beyond ugly... Although, there's no decompiling involved...
9 年多之前 回复
csdnceshi73
喵-见缝插针 What!? creating and decompiling a Function to hack a multiline comment into being a multiline string? Now that's ugly.
9 年多之前 回复
csdnceshi57
perhaps? +1+1 Clever! (works in Node.JS)
9 年多之前 回复

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

csdnceshi79
python小菜 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.
大约 3 年之前 回复
weixin_41568208
北城已荒凉 Are u sure about that? Especially that we have already set it to display:none?
大约 3 年之前 回复
csdnceshi79
python小菜 Just be warned that search engines do still index content in hidden DIVs.
3 年多之前 回复
weixin_41568208
北城已荒凉 Interesting idea, but there's a limitation: you can't put a variable within it. The only stopgap is to do ugly search-and-replace.
3 年多之前 回复
weixin_41568134
MAO-EYE $('#UniqueID').content()
6 年多之前 回复
csdnceshi61
derek5. What if the string is HTML?
6 年多之前 回复
weixin_41568126
乱世@小熊 this gets the work done for me, although it doesnot solve multiline string values assignment to javascript variables
大约 7 年之前 回复
csdnceshi74
7*4 This was the only method that actually worked for me to create a multi-line javascript string variable from a Java String.
大约 7 年之前 回复
csdnceshi53
Lotus@ 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).
7 年多之前 回复

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)

csdnceshi70
笑故挽风 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.
6 年多之前 回复
weixin_41568208
北城已荒凉 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.
接近 7 年之前 回复
csdnceshi78
程序go 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 年之前 回复
weixin_41568174
from.. 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.
大约 8 年之前 回复

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

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";
共30条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐