Ask Ben: Rendering Javascript Line Breaks

Posted July 17, 2008 at 7:27 PM by Ben Nadel

Tags: Javascript / DHTML, Ask Ben

Hi, I am learning Javascript and going through a self paced book. I am trying to use \n for new line in an example program, but it does not work. Here is the snippet:

//Display the current date and time on the web page
document.writeln(todays_date);

if (navigator.appName == "Microsoft Internet Explorer") {
document.write("\nYou are running Microsoft IE")
}else {
if (navigator.appName == "Netscape") {
document.writeln("You are running Netscape")
}
else {
document.writeln("You're not running Microsoft IE or Firefox")
}
}

As you can see I put "\n" before "You are running Microsoft IE", but it does not show the line in an new line. Why is that? Is it because I am using the write method? How do I make this line to show on a new line then? Thanks for your help.

The line break is actually working. The problem you are having is that it is not working in any useful way. If you could look at the "rendered" source of the page, you would notice that there is a line break. However, because a web browser does not inherently render line breaks, the displayed web page does not show you that the line is breaking. You can however, ask the browser to render the code exactly as-is by using something like the PRE tag. Take a look at this example:

  • <!--- Render in standard way. --->
  • <script type="text/javascript">
  • document.write( "-Line one \n-Line two" );
  • </script>
  •  
  • <!--- Renader inside of PRE tags (renders as-is). --->
  • <pre>
  • <script type="text/javascript">
  • document.write( "-Line one \n-Line two" );
  • </script>
  • </pre>

Notice that we have the exact same code in the Javascript, but the second snippet executes within an HTML PRE tag. Running the above code, we get the following output:

-Line one -Line two
-Line one
-Line two

As you can see, the line break in the second output gets rendered while the first one does not.

Now, generally, you don't want to use PRE tags unless you are outputting something like code or CSV files. To get a line break in HTML, you would output the break tag "<br />" instead.

This doesn't mean that the \n character is useless - far from it. The \n does render line breaks in Textareas and any kind of Javascript alert:

  • alert( "-Line one \n-Line two" );

It is also a valid character and can be used inside of Javascript variables. For example, you could take the text of a paragraph and split() it based on the "\n" character to get an array of the individual lines. But in general, you never render the \n character outside of form fields and Javascript alerts.



Reader Comments

Jul 17, 2008 at 8:13 PM // reply »
1 Comments

Or this should work as well

document.write("<br/>You are running Microsoft IE")


Jul 18, 2008 at 6:28 AM // reply »
131 Comments

To expand on Don's point a bit, think of it this way:

1. '\n' is the newline character for JavaScript output, so if you do alert("Error:\nThis is an alert");, then that message will popup on two lines.

2. '<br/>' is the newline character for HTML output, and HTML thinks '\n' is simply two characters to be displayed 'as is'.

HTH


Jul 18, 2008 at 8:05 AM // reply »
10,640 Comments

@JFish,

Well put.


Jul 21, 2008 at 12:41 PM // reply »
1 Comments

i´ve a problem in combination with perl. With /n there comes no linebreak


Jul 21, 2008 at 9:54 PM // reply »
1 Comments

So does CSS white-space:pre-wrap help Javascript \n to render in naked html:

<div style="white-space:pre-wrap;">
<script type="application/javascript">
if (navigator.appName == "Microsoft Internet Explorer") {
document.write("You are running\nMicrosoft IE")
}else {
if (navigator.appName == "Netscape") {
document.writeln("You are running\nNetscape")
} else {
document.writeln("You're not running\nMicrosoft IE or Firefox")
}
}
</script>
</div>


Jul 22, 2008 at 8:41 AM // reply »
10,640 Comments

@Peter,

To be honest, I have never tried that. I would stick with the use of the BR tag to create breaks. I think it is the more "intentful" way to create line breaks in HTML.


Jul 23, 2008 at 5:04 PM // reply »
2 Comments

@Peter

Yes, that should work if the browser is capable of using CSS. That said, it's not the ideal solution.

@no one in particular

\n is a literal return, like pressing the enter key while writing code, it will render a single space in the browser. Paragraph (p) and break (br) tags are preferred to messing with CSS properties. Also note that the return char for Windows is actually 2 chars (think it's line feed and return to home) and in Linux/Unix/BSD/Mac OS it is only one char (just the return, if I remember correctly).


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »
Feb 9, 2012 at 10:29 PM
Learning ColdFusion 9: Application-Specific Data Sources
@Ben, No offence, but if people were really wanting advanced features they would be using a platform like ASP.NET MVC. CFML is so structurally compromised as a tag-based scripting language that ... read »
Feb 9, 2012 at 10:03 PM
Subversion - Cleanup Failed To Process The Following Paths
@Leviaguirre, do you still have problems with this? ... read »