STRINGS
Of all the data types (string, number, boolean, null, object, function) you will work with in JavaScript, strings are probably the most common.
Strings are a Data Type that represent any series of characters between quotes. Form element values are stored as strings, as well as URLs to files and images. Below is an example of a string used as the parameter of the write() method:
document.write("Hello World");
You can use either double quotes or single quotes around strings. You can even mix single and double quotes within a string as long as quotes are nested properly.
"you said, 'hi' to me"
'you said, "hi" to me'
The Escape Character
Some scripters prefer to use only one type of quote to avoid messy quote nesting. It is legal to include the same type of quote as part of a string as long as the escape character is used with it to tell the JavaScript engine that the quote is
part of the string, not the end of it. Placing the escape character "\"
before a quote to be included in the string makes this possible:
"you said, \"hi\" to me"
'you said, \'hi\' to me'
String Variables
The above examples are known as string literals because the text is quoted literally. A string variable then, is a variable name that is assigned to a literal. Quoting string variables is not required or legal.
Below is a statement that will produce the exact same results as the first example, except the variable assigned to the literal is being used as the parameter of the write() method rather than the literal itself.
var stuff = "Hello World"
document.write(stuff)
Take a look at
this example using the write() method to write a text string to the page.
Note about using document.write()
When a document.write() statement is executed after a page has finished loading, the entire page will be overwritten by the write() method's parameter. Knowing this is important for two reasons: first, you will not always want to overwrite an entire page, and second, in the case that you do, you'll need to include a couple lines of code before and after the write statement in order for Netscape 4.x browsers to keep from freezing up. It is known as "opening the stream" and "closing the stream". They are:
function writeStuff() {
var stuff = "Hello World"
document.open();
document.write(stuff);
document.close();
}
<input type="button" onclick="writeStuff()">
This will only occur when the write method is contained within the body of a function that is called from an event handler, or inline within the event handler itself because an event handler cannot be triggered until after a page has loaded completely. However, if a function contains the write method, and the function is invoked naturally within the document flow as the page is loading, overwriting does not occur.
|
Advanced Note: Writing Scripts To A Page Using document.write()
If you want to write a script to a page, special care must be taken when writing the opening and closing script tag pair. When the JavaScript engine encounters a closing script tag, it will exit the script, even if the closing tag is the parameter of a document.write() statement. To work around this, use concatenation (see below) to break up the closing tag. It is also a good idea to do the same thing to the opening tag.
document.write("<scr" + "ipt language=\"javascript\">")
document.write("</scr" + "ipt>")
Sample 1. A script generated page containing another script in this window lesson.
Sample 2. Using eval() to execute scripts.
|
String Concatenation
Binding multiple strings together is known as concatenation. The concatenation operator, "
+" is used to signify that one whole string is to be 'added' to another whole string, be it a literal or a variable. It can be followed by a carriage return or by another string variable or literal.
var myString = "Hello World." +
" My name is Szymon." + " What is your name?"
alert( myString )
var myName = " My name is Szymon."
var myString = "Hello World." + myName + " What is your name?"
alert( myString )
You could also use the string operator, "
+=" after a reference to a string variable to concatenate multiple strings and assign them to the string variable.
var myString = "Hello World"
myString += " My name is Szymon"
myString += " What is your name?"
alert( myString )
Take a look at
this example using concatenation.
Creating Line Breaks
To create line breaks within a string, use "\n" as part of the string. If your string is HTML that will be written to a document, the line break will only create a break in source code, or in a dialog box as in the example below. If you want a line break in text that is to be written to a document, use the HTML break tag in the string ("<br />").
var lineBreakString = "Hello World \nMy name is Szymon \nWhat is your name?"
alert( lineBreakString )
When working with very long strings, tracking bugs such as improper quote nesting or missing escape characters is made easier by breaking the string up into smaller strings. Breaking up a string using the concatenation operator and a carriage return will accomplish the task, but be careful never to use the operator/carriage return pair without closing the string first.
A very practical application of this type of string concatenation is when you use JavaScript to mimic embedded style sheets. Both the opening and closing style tags as well as each rule is stored as a seperate string on its own line for readability. Saving style rules as a JavaScript string in an external .js file, then invoking document.write() to write the style string directly to your page gives you all the benefits of a single linked style sheet, but has the "stickiness" of an embedded style sheet.
var style = '<style type="text/css">\n'+
'.reg { font-size: 10pt; color:#000000; font-family:monospace } \n' +
'.bigRed { font-size: 14pt; color:#ff0000; font-family:monospace } \n' +
'</style>'
document.write(style)
**Do not use \n after the closing style tag or else a strange break in the page will occur with some browsers.
Data Type Conversions
Another common data type is numbers. Mixing numbers with strings can produce unwanted results if you're not careful. When concatenating numbers and strings, JavaScript will usually treat the number as a string.
2 + 2 // result is 4
2 + "2" // result is 22
2 + 2 + "2" // result is 42
Form field values and numbers
Since form element values are stored as strings, performing mathematical operations on numbers that are represented as strings can present a problem. A couple of very handy built-in methods for converting strings to numbers are
parseInt() for integers (whole numbers) and
parseFloat() for floating point numbers (contain decimals).
parseInt("2") + parseInt("2") // result is 4
2 + parseInt("2") // result is 4