Top » REFERENCE » STRINGS If you find this page useful
please make a secure donation
My Account  |  Cart Contents  |  Checkout   

Javascript Reference - Strings

Previous     Contents     Index     Next     
Core JavaScript Reference 1.5





String

An object representing a series of characters in a string.



Core object

Implemented in  

JavaScript 1.0: Create a String object only by quoting characters.

JavaScript 1.1, NES 2.0: added String constructor; added prototype property; added split method; added ability to pass strings among scripts in different windows or frames (in previous releases, you had to add an empty string to another window's string to refer to it).

JavaScript 1.2, NES 3.0: added concat, match, replace, search, slice, and substr methods.

JavaScript 1.3: added toSource method; changed charCodeAt, fromCharCode, and replace methods.  

ECMA version  

ECMA-262  


Created by
The String constructor:

new String(string)


Parameters



string

 

Any string.  


Description
The 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:

s1 = "foo" // creates a string literal value
s2 = new String("foo") // creates a String object

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:

s1 = "2 + 2" // creates a string literal value
s2 = new String("2 + 2") // creates a String object
eval(s1)     // returns the number 4
eval(s2)     // returns the string "2 + 2"

A string can be represented as a literal enclosed by single or double quotation marks; for example, "Netscape" or `Netscape'.

You can convert the value of any object into a string using the top-level String function.


Property Summary



Property

Description

constructor

 

Specifies the function that creates an object's prototype.  

length

 

Reflects the length of the string.  

prototype

 

Allows the addition of properties to a String object.  


Method Summary



Method

Description

anchor

 

Creates an HTML anchor that is used as a hypertext target.  

big

 

Causes a string to be displayed in a big font as if it were in a BIG tag.  

blink

 

Causes a string to blink as if it were in a BLINK tag.  

bold

 

Causes a string to be displayed as if it were in a B tag.  

charAt

 

Returns the character at the specified index.  

charCodeAt

 

Returns a number indicating the Unicode value of the character at the given index.  

concat

 

Combines the text of two strings and returns a new string.  

fixed

 

Causes a string to be displayed in fixed-pitch font as if it were in a TT tag.  

fontcolor

 

Causes a string to be displayed in the specified color as if it were in a <FONT COLOR=color> tag.  

fontsize

 

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

fromCharCode

 

Returns a string created by using the specified sequence of Unicode values. This is a method on the String class, not on a String instance.  

indexOf

 

Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.  

italics

 

Causes a string to be italic, as if it were in an I tag.  

lastIndexOf

 

Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.  

link

 

Creates an HTML hypertext link that requests another URL.  

match

 

Used to match a regular expression against a string.  

replace

 

Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.  

search

 

Executes the search for a match between a regular expression and a specified string.  

slice

 

Extracts a section of a string and returns a new string.  

small

 

Causes a string to be displayed in a small font, as if it were in a SMALL tag.  

split

 

Splits a String object into an array of strings by separating the string into substrings.  

strike

 

Causes a string to be displayed as struck-out text, as if it were in a STRIKE tag.  

sub

 

Causes a string to be displayed as a subscript, as if it were in a SUB tag.  

substr

 

Returns the characters in a string beginning at the specified location through the specified number of characters.  

substring

 

Returns the characters in a string between two indexes into the string.  

sup

 

Causes a string to be displayed as a superscript, as if it were in a SUP tag.  

toLowerCase

 

Returns the calling string value converted to lowercase.  

toSource

 

Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the Object.toSource method.  

toString

 

Returns a string representing the specified object. Overrides the Object.toString method.  

toUpperCase

 

Returns the calling string value converted to uppercase.  

valueOf

 

Returns the primitive value of the specified object. Overrides the Object.valueOf method.  

In addition, this object inherits the watch and unwatch methods from Object.


Examples
Example 1: String literal. The following statement creates a string literal:

var last_name = "Schaefer"

Example 2: String literal properties. The following statements evaluate to 8, "SCHAEFER," and "schaefer":

last_name.length
last_name.toUpperCase()
last_name.toLowerCase()

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:

var lastName = "Schaefer"
var firstName = "Jesse"
empWindow=window.open('string2.html','window1','width=300,height=300')

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:

alert('empFirstName in empWindow is ' + empWindow.empFirstName)
alert('empLastName in empWindow is ' + empWindow.empLastName)


anchor

Creates an HTML anchor that is used as a hypertext target.



Method of  

String  

Implemented in  

JavaScript 1.0, NES 2.0  


Syntax
anchor(nameAttribute)


Parameters



nameAttribute

 

A string.  


Description
Use 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.


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

var myString="Table of Contents"
msgWindow.document.writeln(myString.anchor("contents_anchor"))

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

<A NAME="contents_anchor">Table of Contents</A>


See also
String.link


big

Causes a string to be displayed in a big font as if it were in a BIG tag.



Method of  

String  

Implemented in  

JavaScript 1.0, NES 2.0  


Syntax
big()


Parameters
None


Description
Use the big 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.


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

var worldString="Hello, world"

document.write(worldString.small())
document.write("<P>" + worldString.big())
document.write("<P>" + worldString.fontsize(7))

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

<SMALL>Hello, world</SMALL>
<P><BIG>Hello, world</BIG>
<P><FONTSIZE=7>Hello, world</FONTSIZE>


See also
String.fontsize, String.small


blink

Causes a string to blink as if it were in a BLINK tag.



Method of  

String  

Implemented in  

JavaScript 1.0, NES 2.0  


Syntax
blink()


Parameters
None


Description
Use the blink 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.


Examples
The following example uses string methods to change the formatting of a string:

var worldString="Hello, world"

document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())

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

<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>


See also
String.bold, String.italics, String.strike


bold

Causes a string to be displayed as bold as if it were in a B tag.



Method of  

String  

Implemented in  

JavaScript 1.0, NES 2.0  


Syntax
bold()


Parameters
None


Description
Use the bold 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.


Examples
The following example uses string methods to change the formatting of a string:

var worldString="Hello, world"
document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())

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

<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>


See also
String.blink, String.italics, String.strike


charAt

Returns the specified character from the string.



Method of  

String  

Implemented in  

JavaScript 1.0, NES 2.0  

ECMA version  

ECMA-262  


Syntax
charAt(index)


Parameters



index

 

An integer between 0 and 1 less than the length of the string.  


Description
Characters 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.


Examples
The 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


See also
String.indexOf, String.lastIndexOf, String.split


charCodeAt

Returns a number indicating the Unicode value of the character at the given index.



Method of  

String  

Implemented in  

JavaScript 1.2, NES 3.0

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

ECMA version  

ECMA-262  


Syntax
charCodeAt([index])


Parameters



index

 

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


Description
Unicode 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.


Example
The following example returns 65, the Unicode value for A.

"ABC".charCodeAt(0) // returns 65


concat

Combines the text of two or more strings and returns a new string.



Method of  

String  

Implemented in  

JavaScript 1.2, NES 3.0  


Syntax
concat(string2, string3[, ..., stringN])


Parameters



string2...
stringN

 

Strings to concatenate to this string.  


Description
concat combines the text from one or more strings and returns a new string. Changes to the text in one string do not affect the other string.


Example
The following example combines two strings into a new string.

s1="Oh "
s2="what a beautiful "
s3="mornin'."
s4=s1.concat(s2,s3) // returns "Oh what a beautiful mornin'."


constructor

Specifies the function that creates an object's prototype. Note that the value of this property is a reference to the function itself, not a string containing the function's name.



Property of  

String  

Implemented in  

JavaScript 1.1, NES 2.0  

ECMA version  

ECMA-262  


Description
See Object.constructor.


fixed

Causes a string to be displayed in fixed-pitch font as if it were in a TT tag.



Method of  

String  

Implemented in  

JavaScript 1.0, NES 2.0  


Syntax
fixed()


Parameters
None


Description
Use the fixed 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.


Examples
The following example uses the fixed method to change the formatting of a string:

var worldString="Hello, world"
document.write(worldString.fixed())

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

<TT>Hello, world</TT>


fontcolor

Causes a string to be displayed in the specified color as if it were in a <FONT COLOR=color> tag.



Method of  

String  

Implemented in  

JavaScript 1.0, NES 2.0  


Syntax
fontcolor(color)


Parameters



color

 

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.  


Description
Use 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.


Examples
The 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.



Method of  

String  

Implemented in  

JavaScript 1.0, NES 2.0  


Syntax
fontsize(size)


Parameters



size

 

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


Description
Use 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.


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

var worldString="Hello, world"

document.write(worldString.small())
document.write("<P>" + worldString.big())
document.write("<P>" + worldString.fontsize(7))

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

<SMALL>Hello, world</SMALL>
<P><BIG>Hello, world</BIG>
<P><FONTSIZE=7>Hello, world</FONTSIZE>


See also
String.big, String.small


fromCharCode

Returns a string created by using the specified sequence of Unicode values.



Method of  

String  

Static

Implemented in  

JavaScript 1.2, NES 3.0

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

ECMA version  

ECMA-262  


Syntax
fromCharCode(num1, ..., numN)


Parameters



num1, ..., numN

 

A sequence of numbers that are Unicode values.  


Description
This method returns a string and not a String object.

Because fromCharCode is a static method of String, you always use it as String.fromCharCode(), rather than as a method of a String object you created.


Backward Compatibility

JavaScript 1.2. The fromCharCode method returns a string created by using the specified sequence of ISO-Latin-1 codeset values.


Examples
The following example returns the string "ABC".

String.fromCharCode(65,66,67)


indexOf

Returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex, or -1 if the value is not found.



Method of  

String  

Implemented in  

JavaScript 1.0, NES 2.0  

ECMA version  

ECMA-262  


Syntax
indexOf(searchValue[, fromIndex])


Parameters



searchValue

 

A string representing the value to search for.  

fromIndex

 

The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0.  


Description
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character of a string called stringName is stringName.length - 1.

"Blue Whale".indexOf("Blue")    // returns 0
"Blue Whale".indexOf("Blute")   // returns -1
"Blue Whale".indexOf("Whale",0) // returns 5
"Blue Whale".indexOf("Whale",5) // returns 5
"Blue Whale".indexOf("",9)      // returns 9
"Blue Whale".indexOf("",10)     // returns 10
"Blue Whale".indexOf("",11)     // returns 10

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

"Blue Whale".indexOf("blue")


Examples
Example 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.

myString="brie, pepper jack, cheddar"
myCapString="Brie, Pepper Jack, Cheddar"
document.writeln('myString.indexOf("cheddar") is ' +
   myString.indexOf("cheddar"))
document.writeln('<P>myCapString.indexOf("cheddar") is ' +
   myCapString.indexOf("cheddar"))

Example 3. The following example sets count to the number of occurrences of the letter x in the string str:

count = 0;
pos = str.indexOf("x");
while ( pos != -1 ) {
   count++;
   pos = str.indexOf("x",pos+1);
}


See also
String.charAt, String.lastIndexOf, String.split


italics

Causes a string to be italic, as if it were in an <I> tag.



Method of  

String  

Implemented in  

JavaScript 1.0, NES 2.0  


Syntax
italics()


Parameters
None


Description
Use the italics 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.


Examples
The following example uses string methods to change the formatting of a string:

var worldString="Hello, world"

document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())

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

<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>


See also
String.blink, String.bold, String.strike


lastIndexOf

Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. The calling string is searched backward, starting at fromIndex.



Method of  

String  

Implemented in  

JavaScript 1.0, NES 2.0  

ECMA version  

ECMA-262  


Syntax
lastIndexOf(searchValue[, fromIndex])


Parameters



searchValue

 

A string representing the value to search for.  

fromIndex

 

The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is the length of the string.  


Description
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character is stringName.length - 1.

"canal".lastIndexOf("a")   // returns 3
"canal".lastIndexOf("a",2) // returns 1
"canal".lastIndexOf("a",0) // returns -1
"canal".lastIndexOf("x")   // returns -1

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

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


Examples
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"))


See also
String.charAt, String.indexOf, String.split


length

The length of the string.



Property of  

String  

Read-only

Implemented in  

JavaScript 1.0, NES 2.0  

ECMA version  

ECMA-262  


Description
For a null string, length is 0.


Examples
The following example displays 8 in an Alert dialog box:

var x="Netscape"
alert("The string length is " + x.length)


link

Creates an HTML hypertext link that requests another URL.



Method of  

String  

Implemented in  

JavaScript 1.0, NES 2.0  


Syntax
link(hrefAttribute)


Parameters



hrefAttribute

 

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


Description
Use 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.


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

var hotText="Netscape"
var URL="http://home.netscape.com"

document.write("Click to return to " + hotText.link(URL))

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

Click to return to <A href="/page/reference__http://home.netscape.com">Netscape</A>


match

Used to match a regular expression against a string.



Method of  

String  

Implemented in  

JavaScript 1.2  

ECMA version  

ECMA-262 Edition 3  


Syntax
match(regexp)


Parameters



regexp

 

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


Description
If 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.

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