DescriptionThe String object is a wrapper around the string primitive data type. Do not confuse a string literal with the String object. For example, the following code creates the string literal s1 and also the String object s2:

You can call any of the methods of the String object on a string literal value-JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property with a string literal.

You should use string literals unless you specifically need to use a String object, because String objects can have counterintuitive behavior. For example:

Example 3: Accessing individual characters in a string. You can think of a string as an array of characters. In this way, you can access the individual characters in the string by indexing that array. For example, the following code displays "The first character in the string is H":

var myString = "Hello"
myString[0] // returns "H"

Example 4: Pass a string among scripts in different windows or frames. The following code creates two string variables and opens a second window:

If the HTML source for the second window (string2.html) creates two string variables, empLastName and empFirstName, the following code in the first window assigns values to the second window's variables:

empWindow.empFirstName=firstName
empWindow.empLastName=lastName

The following code in the first window displays the values of the second window's variables:

DescriptionUse the anchor method with the document.write or document.writeln methods to programmatically create and display an anchor in a document. Create the anchor with the anchor method, and then call write or writeln to display the anchor in a document. In server-side JavaScript, use the write function to display the anchor.

In the syntax, the text string represents the literal text that you want the user to see. The nameAttribute string represents the NAME attribute of the A tag.

Anchors created with the anchor method become elements in the document.anchors array.

ExamplesThe following example opens the msgWindow window and creates an anchor for the table of contents:

DescriptionCharacters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string called stringName is stringName.length - 1. If the index you supply is out of range, JavaScript returns an empty string.

ExamplesThe following example displays characters at different locations in the string "Brave new world":

var anyString="Brave new world"

document.writeln("The character at index 0 is " + anyString.charAt(0))
document.writeln("The character at index 1 is " + anyString.charAt(1))
document.writeln("The character at index 2 is " + anyString.charAt(2))
document.writeln("The character at index 3 is " + anyString.charAt(3))
document.writeln("The character at index 4 is " + anyString.charAt(4))

These lines display the following:

The character at index 0 is B
The character at index 1 is r
The character at index 2 is a
The character at index 3 is v
The character at index 4 is e

JavaScript 1.3: returns a Unicode value rather than an ISO-Latin-1 value.

ECMA version

ECMA-262

SyntaxcharCodeAt([index])

Parameters

index

An integer between 0 and 1 less than the length of the string. The default value is 0.

DescriptionUnicode values range from 0 to 65,535. The first 128 Unicode values are a direct match of the ASCII character set. For information on Unicode, see the Core JavaScript Guide.

Backward Compatibility

JavaScript 1.2.The charCodeAt method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from 0 to 255. The first 0 to 127 are a direct match of the ASCII character set.

A string expressing the color as a hexadecimal RGB triplet or as a string literal. String literals for color names are listed in the Core JavaScript Guide.

DescriptionUse the fontcolor method with the write or writeln methods to format and display a string in a document. In server-side JavaScript, use the write function to display the string.

If you express color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".

The fontcolor method overrides a value set in the fgColor property.

ExamplesThe following example uses the fontcolor method to change the color of a string:

var worldString="Hello, world"

document.write(worldString.fontcolor("maroon") +
" is maroon in this line")
document.write("<P>" + worldString.fontcolor("salmon") +
" is salmon in this line")
document.write("<P>" + worldString.fontcolor("red") +
" is red in this line")

document.write("<P>" + worldString.fontcolor("8000") +
" is maroon in hexadecimal in this line")
document.write("<P>" + worldString.fontcolor("FA8072") +
" is salmon in hexadecimal in this line")
document.write("<P>" + worldString.fontcolor("FF00") +
" is red in hexadecimal in this line")

The previous example produces the same output as the following HTML:

<FONT COLOR="maroon">Hello, world</FONT> is maroon in this line
<P><FONT COLOR="salmon">Hello, world</FONT> is salmon in this line
<P><FONT COLOR="red">Hello, world</FONT> is red in this line

<FONT COLOR="8000">Hello, world</FONT>
is maroon in hexadecimal in this line
<P><FONT COLOR="FA8072">Hello, world</FONT>
is salmon in hexadecimal in this line
<P><FONT COLOR="FF00">Hello, world</FONT>
is red in hexadecimal in this line

fontsize

Causes a string to be displayed in the specified font size as if it were in a <FONT SIZE=size> tag.

An integer between 1 and 7, a string representing a signed integer between 1 and 7.

DescriptionUse the fontsize method with the write or writeln methods to format and display a string in a document. In server-side JavaScript, use the write function to display the string.

When you specify size as an integer, you set the size of stringName to one of the 7 defined sizes. When you specify size as a string such as "-2", you adjust the font size of stringName relative to the size set in the BASEFONT tag.

ExamplesThe following example uses string methods to change the size of a string:

The indexOf method is case sensitive. For example, the following expression returns -1:

"Blue Whale".indexOf("blue")

ExamplesExample 1. The following example uses indexOf and lastIndexOf to locate values in the string "Brave new world."

var anyString="Brave new world"

// Displays 8
document.write("<P>The index of the first w from the beginning is " +
anyString.indexOf("w"))
// Displays 10
document.write("<P>The index of the first w from the end is " +
anyString.lastIndexOf("w"))
// Displays 6
document.write("<P>The index of 'new' from the beginning is " +
anyString.indexOf("new"))
// Displays 6
document.write("<P>The index of 'new' from the end is " +
anyString.lastIndexOf("new"))

Example 2. The following example defines two string variables. The variables contain the same string except that the second string contains uppercase letters. The first writeln method displays 19. But because the indexOf method is case sensitive, the string "cheddar" is not found in myCapString, so the second writeln method displays -1.

The lastIndexOf method is case sensitive. For example, the following expression returns -1:

"Blue Whale, Killer Whale".lastIndexOf("blue")

ExamplesThe following example uses indexOf and lastIndexOf to locate values in the string "Brave new world."

var anyString="Brave new world"

// Displays 8
document.write("<P>The index of the first w from the beginning is " +
anyString.indexOf("w"))
// Displays 10
document.write("<P>The index of the first w from the end is " +
anyString.lastIndexOf("w"))
// Displays 6
document.write("<P>The index of 'new' from the beginning is " +
anyString.indexOf("new"))
// Displays 6
document.write("<P>The index of 'new' from the end is " +
anyString.lastIndexOf("new"))

Any string that specifies the HREF attribute of the A tag; it should be a valid URL (relative or absolute).

DescriptionUse the link method to programmatically create a hypertext link, and then call write or writeln to display the link in a document. In server-side JavaScript, use the write function to display the link.

Links created with the link method become elements in the links array of the document object. See document.links.

ExamplesThe following example displays the word "Netscape" as a hypertext link that returns the user to the Netscape home page:

Name of the regular expression. It can be a variable name or a literal.

DescriptionIf the regular expression does not include the g flag, returns the same result that RegExp.exec would return on the regular expression and string. If the regular expression includes the g flag, returns an array of all the matches of the regular expression in the string.

NoteIf you execute a match simply to find true or false, use String.search or the regular expression test method.

ExamplesExample 1. In the following example, match is used to find 'Chapter' followed by 1 or more numeric characters followed by a decimal point and numeric character 0 or more times. The regular expression includes the i flag so that case will be ignored.

JavaScript 1.3: added the ability to specify a function as the second parameter.

ECMA version

ECMA-262 Edition 3

Syntaxreplace(regexp, newSubStr)
replace(regexp, function)

Versions prior to JavaScript 1.3:

replace(regexp, newSubStr)

Parameters

regexp

The name of the regular expression. It can be a variable name or a literal.

newSubStr

The string to put in place of the string found with regexp.

function

A function to be invoked after the match has been performed.

DescriptionThis method does not change the String object it is called on. It simply returns a new string.

If you want to execute a global search and replace, include the g flag in the regular expression.

Specifying a string as a parameter.The replacement string can include the following special replacement patterns:

$$

Inserts a '$'.

$&

Inserts the matched substring..

$`

Inserts the portion of the string that precedes the matched substring.

$´

Inserts the portion of the string that follows the matched substring.

$n
or
$nn

Where n or nn are decimal digits, inserts the nth parenthesized submatch string.

Specifying a function as a parameter.When you specify a function as the second parameter, the function is invoked after the match has been performed. (The use of a function in this manner is often called a lambda expression.)

In your function, you can dynamically generate the string that replaces the matched substring. The result of the function call is used as the replacement value.

The nested function can use the matched substrings to determine the new string (newSubStr) that replaces the found substring. You get the matched substrings through the parameters of your function. The first parameter of your function holds the complete matched substring. The following n parameters can be used for parenthetical matches, remembered submatch strings, where n is the number of submatch strings in the regular expression. Finally, the last two parameters are the offset within the string where the match occurred and the string itself. For example, the following replace method returns XX.zzzz - XX , zzzz.

Example 4. The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function returns 100C. If the number is 0F, the function returns -17.77777777777778C.

The regular expression test checks for any number that ends with F. The number of Fahrenheit degree is accessible to your function through the parameter $1. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the f2c function. f2c then returns the Celsius number. This function approximates Perl's s///e flag.

When you want to know whether a pattern is found in a string use search (similar to the regular expression test method); for more information (but slower execution) use match (similar to the regular expression exec method).

ExampleThe following example prints a message which depends on the success of the test.

Specifies the character to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted, the array returned contains one element consisting of the entire string.

limit

Integer specifying a limit on the number of splits to be found.

DescriptionThe split method returns the new array.

When found, separator is removed from the string and the substrings are returned in an array. If separator is omitted, the array contains one element consisting of the entire string.

In JavaScript 1.2 or later, split has the following additions:

It can take a regular expression argument, as well as a fixed string, by which to split the object string. If separator is a regular expression, any included parenthesis cause submatches to be included in the returned array.

It can take a limit count so that the resulting array does not include trailing empty elements.

If you specify LANGUAGE="JavaScript1.2" in the SCRIPT tag, string.split(" ") splits on any run of 1 or more white space characters including spaces, tabs, line feeds, and carriage returns. For this behavior, LANGUAGE="JavaScript1.2" must be specified in the <SCRIPT> tag.

ExamplesExample 1. The following example defines a function that splits a string into an array of strings using the specified separator. After splitting the string, the function displays messages indicating the original string (before the split), the separator used, the number of elements in the array, and the individual array elements.

Without LANGUAGE="JavaScript1.2", this script splits only on single space characters, producing

"She", "sells", , , , "seashells", "by", , , "the", "seashore"

Example 3. In the following example, split looks for 0 or more spaces followed by a semicolon followed by 0 or more spaces and, when found, removes the spaces from the string. nameList is the array returned as a result of split.

Descriptionstart is a character index. The index of the first character is 0, and the index of the last character is 1 less than the length of the string. substr begins extracting characters at start and collects length number of characters.

If start is positive and is the length of the string or longer, substr returns no characters.

If start is negative, substr uses it as a character index from the end of the string. If start is negative and abs(start) is larger than the length of the string, substr uses 0 is the start index.

If length is 0 or negative, substr returns no characters. If length is omitted, start extracts characters to the end of the string.

Example 2. The following example replaces a substring within a string. It will replace both individual characters and substrings. The function call at the end of the example changes the string "Brave New World" into "Brave New Web".

DescriptionThe String object overrides the toString method of the Object object; it does not inherit Object.toString. For String objects, the toString method returns a string representation of the object.

ExamplesThe following example displays the string value of a String object: