|
Strings are a common programming language concept. A few string examples
include:
"abc"
'123'
"file.txt"
JavaScript allows strings to be delimited by either double quotes or
single quotes. The availability of two string delimiters is particularly
because it allows the use of quotes within a string - without resorting
to special characters. In this next example, the use of double quotes
is possible because the entire string is delimited by single quotes:
x = 'He said "Hello" to me'
Strings are Objects
In JavaScript, unlike many languages, strings are also objects,
which means that all strings come with built-in properties and methods
which can be accessed with JavaScript code.
For example, the length of a string (number of characters) can be assigned
to a variable like this:
x = "123".length
or
z = "abcde" //z is a string variable
y = z.length //y equals the number of characters in z
A full listing of properties and methods of string objects is given
below.
Declaring a String Variable
As with any variable, string variables can be used without
prior declaration. Strings can be declared in two ways,
as shown in this next example:
x = new String("Yes") //both of these are equivalent
x = "yes" //creates object just like above
Combining Strings Operations
To combine two strings, use the string concatenation operator,
which is the plus sign (+), as shown in this next example:
a = b+c+d;
document.writeln(bold_tech + " ");
Escape Characters
Some characters, such as a TAB, do not have a keyboard
characters which can appear inside a string. To support
such characters JavaScript supports what are called
escape characters. An escape characters is simply a
keyboard character preceded by a backslash, as in the
following example:
x = "123\t456"
In this example, the '\t' escape character is used. JavaScript
detects escape characters and makes the appropriate substitutions.
Here are some common escape characters used by JavaScript
programmers:
\n // newline
\t // tab
\" // double quote
\' // single quote
\\ // backslash
String Object Properties and Methods
Here is a list of the properties and methods available to a string.
Note that strings are zero-based - the leftmost characters position
is zero. Also, to apply multiple methods, take a look at the following
example:
MyString.italics().bold().fontcolor("red")
In this example, MyString is made italic, then bold,
and then colored red.
- Properties
- Methods
Formatting
- anchor()
- anchor()
- big()
- blink()
- bold()
- fixed()
- fontcolor()
- fontsize()
- italics()
- link()
- small()
- strike()
- sub()
- sup()
Substrings (find)
- indexOf()
- lastIndexOf()
Substrings (extract)
- charAt()
- slice()
- substr()
- charCodeAt()
- split()
- substring()
RegExpression
- match()
- replace()
- search()
Other
- concat()
- toLowerCase()
- fromCharCode()
|