Strings are created using the global object constructor
String or created as string primitives.
String literals are string primitives and are created by enclosing some value in single or double quotes and are the preferred method of string creation unless you specifically need to use a
Any string primitives have full access to
String objects when a
String method is called on the string primitive. Lets see an example of this.
// Create a String object. aString = new String('happychappy'); // Will show the value 'y' in alert box alert(aString.charAt(4) + ' - String object'); // Create a string literal and call a
String()method on it. bString = 'happychappy'; // Will show the value 'y' in alert box alert(bString.charAt(4) ' + ' - string literal');
There are a few things to remember when concatenating strings together:
The following code should shed light on the above.
// Create a string and numeric variables. var aString = '5'; var aNumber = 5; // Concatenation ends up with a string holding the value '55' not 10. alert(aString + aNumber);
Don't worry about the conditional statements such as
if for now as we cover this in
// Create a couple of strings with same value var aString = 'String'; var bString = 'String'; // Compare strings and alert with a message if (aString < bString) alert(aString + ' is less than ' + bString); else if (aString > bString) alert(aString + ' is greater than ' + bString); else alert(aString + ' and ' + bString + ' have equal string values'); // true
Special Character Usage in Strings
The following are escape character constants that may be required for rendering or printing and use the backslash symbol
\ to signify the escape sequence.
|Escape a backspace|
|Escape a form feed|
|Escape a new line|
|Escape a carriage return|
|Escape a tab|
|Escape a vertical tab|
|Escape a single quote|
|Escape a double quote|
|Escape a backslash|
|Escape the character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF|
|Escape the character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377|
|Escape the Unicode character specified by the four hexadecimal digits XXXX|
Reviewing The Code
There are various ways we can create and manipulate strings and we have shown some examples above. For a complete list of the methods available with the
object and their usage visit the reference section of the site.
Lesson 8 Complete
In this lesson we looked at the
String object and string literals and some of the methods used for extracting data stored within them.