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).
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).
Share Improve this question asked Jan 16, 2009 at 20:51 PythonPowerPythonPower3 Answers
Reset to default 9Put a \ at the end of each line. Alternatively store it in a div with display:none and then use .html() to retrieve it
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 bine 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./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>