Question

I have a long snippet of HTML I want some javascript variable to equal and for maintainability I want to store it with actual newlines instead of adding \n (or as it is HTML just omitting newline characters). In Python I would do something like:

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

And that would work perfectly. However, I haven't seen a way to do this in JavaScript.

Some additional information: the javascript is in an external .js file and the snippet really is quite huge (~6kb).

Was it helpful?

Solution

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

OTHER TIPS

JavaScript doesn't support multi-line strings in the same manner.

You can use \ to escape a newline for your script, but this is only for developer reading as it won't stay with the string (and most validators will throw errors for it). To keep a newline with the string, you'll still be required to use \n.

If you want the readability, you can combine them:

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

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top