JavaScript multiline text

I have a long HTML snippet. I want some javascript variable to be the same, and for ease of maintenance, I want to save it with the actual newline characters instead of adding \ n (or as HTML, just omitting the newline characters). In Python, I would do something like:

largeString = """Hello This is long!""" 

And that will work just fine. However, I have not seen a way to do this in JavaScript.

Additional information: javascript is in the external .js file, and the fragment is really quite large (~ 6kb).

+4
source share
3 answers

Put a \ at the end of each line. Alternatively, save it in a div with a display: none, and then use .html () to extract it

+9
source

JavaScript does not support multiline strings in the same way.

You can use \ to avoid a new line for your script, but this is read-only by developers, as it will not stay with the line (and most validators will cause errors for it). To save a new line with a line, you still need to use \n .

If you want to read, you can combine them:

 var largeString = '"Hello\n\ This is long!"'; 
+3
source

This will work in Firefox, IE, Safari and Chrome:

 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <div class="crazy_idea" largeString='Hello This is long!' ></div> <script type="text/javascript"> alert($(".crazy_idea").attr("largeString")); </script> 
0
source

All Articles