Outputting Text with JavaScript

In most programming languages, one of the basic capabilities is to output – or display – text. In JavaScript output can be directed to several places including the current document windows and pop-up dialog boxes.

document.write() and document.writeln() Methods

The document object in JavaScript includes two methods designed for outputting text to the client window's document: write() and writeln(). In JavaScript, methods are called by combining the object name with the method name:

document.write("Test");
document.writeln('Test');

A quick look at these examples shows you that strings of text are surrounded by double (or single) quotes and that the two methods (document.write() and document.writeln()) are invoked in the same manner. Opening and closing quotes must be the same type, they must match up – you cannot open with double quotes and close with single quotes or vice versa.

For example, suppose you want the string "Thank you for ordering" written in the window in large type. The HTML <H1> and </H1> tags are one way to generate text in a large font size. Therefore, you could simply use this method call:

      document.write("<H1>Thank you for ordering!</H1>");

Alternatively, you might have constructed a string ("An Example") somewhere else in your JavaScript code and assigned that to a variable, such as example. In this case, you can simply pass the variable example as the parameter to the method call, like this:

      var example = "An Example";

      document.write(example); // would output An Example to the document

NOTE that the write method actually takes a variable number of arguments, rather than just one. If more than one argument is given, each of the arguments is interpreted as a string and written in turn.

document.write("This is Part 1 ", "and this is Part 2 ", "and this is Part 3");

is the same as

document.write("This is Part 1 and this is Part 2 and this is Part 3");

The difference between write() and writeln() is that the writeln() appends a newline character to the end of the output. A newline character is basically like a carriage return. However, keep in mind that these methods output their parameters as HTML. And remember that HTML ignores newline characters when it comes to outputting to the screen.

What does the above mean? It means that HTML does not insert line breaks in screen output unless you specify a line break using either <BR> or <P> tags. Any "natural" line breaks in your HTML code, such as those created when you hit return, are ignored. The only time this is not true (when carriage returns are honored) is for text that resides between <PRE> and </PRE> tags. Those tags define a section of text that is "preformatted," and it appears on-screen in the browser's defined monospace font — a font in which all characters are of equal width (it’s often Courier).

NOTE: Thus, in most cases, there will be no effective difference between the write() and writeln() methods unless your string parameter contains HTML code that places the output within <PRE> and </PRE> tags.

document.write()s in action

<BODY>

This text is plain.<BR>

<B>

<SCRIPT>

document.write("This text is bold.</B>");

</SCRIPT>

Output of the Code

NOTICE that the HTML tags, as well as regular text, can be outputted by the write() method. Notice the <B> and </B> tags can either be output as part of the write() method or left outside the script. In either case, the text and HTML is evaluated in the order it appears in the complete HTML and JavaScript source code.

The steps involved with the browser and document.write():

  1. document.write() "converts" everything to HTML
  2. the browser then interprets the HTML and then renders the HTML

Note: variables can also be outputted through the write() methods (annotated version)

The writeln() method is the same as the write() method except that it adds a carriage return at the end of the string that is being outputted. This is really only relevant inside of <PRE> containers where carriage returns are interpreted in displaying the text.

write() & writeln() inside & outside the PRE tags

In this example, you can see how both text and HTML tags can be output to the current HTML windows using the write() method. Notice the use of both single and double quotes to delimit the start and end of the text strings. In the first call to the write() method, you use the single quotes so that the text string can contain the double quotes required by the <IMG> tag.

Escape characters

Characters like the double quote mark ("), the single quote mark ('), the hard return, tabs, the semi-colon (;), and the ampersand (&) have special meanings within JavaScript. But sometimes you want to use them for their traditional values - to have quotation marks appear around a phrase on the screen, to add a hard return to your text file to make it more readable.

In JavaScript, strings of text, such as those used to produce output with the write() and writeln() methods, can include special keystrokes to represent characters that can’t be typed, such as new lines, tabs, and carriage returns. You can escape the character -- that is, you can tell JavaScript to skip over it — by preceding it with a backslash

The backslash ( \ ) character is JavaScript's escape character. Here's a couple examples of it in use.

You can precede hard returns with the backslash to break up a long text line to make your file easier to read and edit. JavaScript will skip the return because there is a backslash immediately in front of it:

document.write("This is a very long sentence \
which I am writing \
in the browser window and \
it is really a paragraph in length \
and I know that it would \
go on for a very long time \
without breaks.")

Output of the above example - Make sure you check the source code

You can precede double quotes that you want to appear in the text string with the backslash. JavaScript will not try to process the double quotes because there is a backslash immediately in front of it:

document.write("This is where we say \"welcome\" to all our friends.<BR>");
document.
write('This is where we say "welcome" to all our friends.<BR>');
document.
writeln("<PRE>document.writeln() works within the the <PRE> tags.</PRE>");
document.
write("<PRE>document.write() with \\n works within the <PRE> tags.\n</PRE>");
document.
write("document.write() with \\n does not works outside the <PRE> tags.\n");
document.
write("A backslash: \\");

Output of the above example

Escape characters

CHARACTER DESCRIPTION
\n new line
\t tab
\r carriage return
\f form feed
\b backspace

NOTE: the escape characters only work in the following situations:

Double and Single Quotes

Use double quotes (") for HTML attributes and single quotes (') for JavaScript string literals.

When writing HTML it is general practice to use double quotes for tag attributes, e.g.:

<IMG SRC="picture.gif" WIDTH="400" HEIGHT="400">

When writing JavaScript it is general practice to use single quotes for string literals:

<SCRIPT>

document.write('<P>');

</SCRIPT>

In general these quoting styles then complement one another when outputting HTML using JavaScript:

<SCRIPT>

document.write('<IMG SRC="picture.gif" WIDTH="400" HEIGHT="400">');

// -- OR --
// document.write("<IMG SRC=\"picture.gif\" WIDTH=\"400\" HEIGHT=\"400\">");

</SCRIPT>

Where nested quotes are required then use the escape key ("\") to escape the quotes:

<SCRIPT>

document.write('Don\'t forget to escape apostrophes');

</SCRIPT>

Concatenation – you can combine the various pieces of your welcome message into a single document.write() command using a simple plus (+):

document.write('<IMG SRC="welcome.gif">');
document.write("<H3>Greetings, "
                          + prompt("Enter Your Name:", "Frank")
                          + ". Welcome to the " + navigator.appName + "!</H3>");

*** prompt() message & concatenation ***