4

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

asked Jan 16, 2009 at 20:51

3 Answers 3

9

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

answered Jan 16, 2009 at 20:56
Sign up to request clarification or add additional context in comments.

1 Comment

Here is exaple of using \ and storing in div forums.devx.com/showthread.php?t=154826
3

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!"';
answered Jan 16, 2009 at 20:58

Comments

0

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>
answered Nov 23, 2010 at 17:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.