最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Multiline JavaScript Text - Stack Overflow

programmeradmin3浏览0评论

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 PythonPowerPythonPower
Add a ment  | 

3 Answers 3

Reset to default 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

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>
发布评论

评论列表(0)

  1. 暂无评论