[Contents]

String

An object representing a series of characters in a string.

Created by

The String constructor:

new String(string);

Parameters

string
Any string.

Description

The String object is a built-in JavaScript object. You an treat any JavaScript string as a String object.

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

Property Summary

length
Reflects the length of the string.

prototype
Allows the addition of properties to a String object.

Method Summary

anchor
Creates an HTML A tag.

big
Creates an HTML BIG tag.

blink
Creates an HTML BLINK tag.

bold
Creates an HTML BOLD tag.

charAt
Returns the character at the specified index.

charCodeAt
Returns a number indicating the ISO-Latin-1 codeset value of the character at the given index.

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

fixed
Creates an HTML TT tag.

fontcolor
Creates an HTML FONT COLOR tag.

fontsize
Creates an HTML FONT SIZE tag.

fromCharCode
Returns a string from the specified sequence of numbers that are ISO-Latin-1 codeset values.

indexOf
Returns the index within the calling String object of the first occurrence of the specified value.

italics
Creates an HTML I tag.

lastIndexOf
Returns the index within the calling String object of the last occurrence of the specified value.

link
Creates an HTML A HREF tag.

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
Creates an HTML SMALL tag.

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

strike
Creates an HTML STRIKE tag.

sub
Creates an HTML 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
Creates an HTML SUP tag.

toLowerCase
Returns the calling string value converted to lowercase.

toUpperCase
Returns the calling string value converted to uppercase.

Examples

Example 1: String variable. The following statement creates a string variable:

var last_name = "Schaefer"
Example 2: String object 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:

var myString = "Hello"
"The first character in the string is " + myString[0]
displays "The first character in the string is H"

Properties

length

The length of the string.

Property of

String

Read-only

Description

For a null string, length is 0.

Examples

The following example displays "The string length is 8":

var x="Netscape"
"The string length is " + x.length

prototype

Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For information on prototypes, see Function.prototype.

Property of

String

Methods

anchor

Creates an HTML A tag.

Method of

String

Syntax

anchor(nameAttribute)

Parameters

nameAttribute
A string.

Description

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.

Examples

The following example creates an anchor for the table of contents:

var myString="Table of Contents"
myString.anchor("contents_anchor")
The previous example produces the following output:

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

See also

String.link

big

Creates an HTML BIG tag.

Method of

String

Syntax

big()

Parameters

None

Examples

var worldString="Hello, world"
worldString.big()
The previous example produces the following outputs:

<BIG>Hello, world</BIG>

See also

String.fontsize, String.small

blink

Creates an HTML BLINK tag.

Method of

String

Syntax

blink()

Parameters

None

Examples

var worldString="Hello, world"
worldString.blink()
The previous example produces the following output:

<BLINK>Hello, world</BLINK>

See also

String.bold, String.italics, String.strike

bold

Creates an HTML B tag.

Method of

String

Syntax

bold()

Parameters

None

Examples

var worldString="Hello, world"
worldString.bold()
The previous example produces the following output:

<B>Hello, world</B>

See also

String.blink, String.italics, String.strike

charAt

Returns the specified character from the string.

Method of

String

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"
"The character at index 0 is " + anyString.charAt(0)
"The character at index 1 is " + anyString.charAt(1)
"The character at index 2 is " + anyString.charAt(2)
"The character at index 3 is " + anyString.charAt(3)
"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 ISO-Latin-1 codeset value of the character at the given index.

Method of

String

Syntax

charCodeAt(index)

Parameters

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

Description

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 ISO-Latin-1 codeset value for A.

"ABC".charCodeAt(0)

concat

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

Method of

String

Syntax

concat(string2)

Parameters

string1
The first string.

string2
The second string.

Description

concat combines the text from two 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.


str1="The morning is upon us. "
str2="The sun is bright."
str3=str1.concat(str2)
This writes:

The morning is upon us.
The sun is bright.
The morning is upon us. The sun is bright.

fixed

Creates an HTML TT tag.

Method of

String

Syntax

fixed()

Parameters

None

Examples

var worldString="Hello, world"
worldString.fixed()
The previous example produces the following output:

<TT>Hello, world</TT>

fontcolor

Creates an HTML FONT COLOR tag.

Method of

String

Syntax

fontcolor(color)

Parameters

color
A string expressing the color as a hexadecimal RGB triplet or as a string literal.

Description

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".

Examples

var worldString="Hello, world"
worldString.fontcolor("maroon")
worldString.fontcolor("FA8072")
The previous examples produce the following output:

<FONT COLOR="maroon">Hello, world</FONT>
<FONT COLOR="FA8072">Hello, world</FONT>

fontsize

Creates an HTML FONT SIZE tag.

Method of

String

Syntax

fontsize(size)

Parameters

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

Description

Examples

var worldString="Hello, world"
worldString.fontsize(7)
The previous example produces the following output:

<FONTSIZE=7>Hello, world</FONTSIZE>

See also

String.big, String.small

fromCharCode

Returns a string created by using the specified sequence ISO-Latin-1 codeset values.

Method of

String

Static

Syntax

fromCharCode(num1, ..., numN)

Parameters

num1, ..., numN
A sequence of numbers that are ISO-Latin-1 codeset 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.

Example

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

Syntax

indexOf(searchValue, fromIndex)

Parameters

searchValue
A string representing the value to search for.

fromIndex
(Optional) The location within the calling string to start the search from. It can be any integer between 0 and 1 less than 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.

If stringName contains an empty string (""), indexOf returns an empty string.

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
"The index of the first w from the beginning is " +
   anyString.indexOf("w")
//Displays 10
"The index of the first w from the end is " +
   anyString.lastIndexOf("w")
//Displays 6
"The index of 'new' from the beginning is " +
   anyString.indexOf("new")
//Displays 6
"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 indexOf call returns 19. But because the indexOf method is case sensitive, the string "cheddar" is not found in myCapString, so the second indexOf call returns -1.

myString="brie, pepper jack, cheddar"
myCapString="Brie, Pepper Jack, Cheddar"
'myString.indexOf("cheddar") is ' +
   myString.indexOf("cheddar")
'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

Creates an HTML I tag.

Method of

String

Syntax

italics()

Parameters

None

Examples

var worldString="Hello, world"
worldString.italics()
The previous example produces the following output:

<I>Hello, world</I>

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. The calling string is searched backward, starting at fromIndex, or -1 if not found.

Method of

String

Syntax

lastIndexOf(searchValue, fromIndex)

Parameters

searchValue
A string representing the value to search for.

fromIndex
(Optional) The location within the calling string to start the search from. It can be any integer between 0 and 1 less than the length of the string. The default value is 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 is stringName.length - 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
"The index of the first w from the beginning is " +
   anyString.indexOf("w")
//Displays 10
"The index of the first w from the end is " +
   anyString.lastIndexOf("w")
//Displays 6
"The index of 'new' from the beginning is " +
   anyString.indexOf("new")
//Displays 6
"The index of 'new' from the end is " +
   anyString.lastIndexOf("new")

See also

String.charAt, String.indexOf, String.split

link

Creates an HTML A HREF tag.

Method of

String

Syntax

link(hrefAttribute)

Examples

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

var hotText="Netscape"
var URL="http://home.netscape.com"
hotText.link(URL)
The previous example produces the following output:

<A HREF="http://home.netscape.com">Netscape</A>

See also

Anchor

match

Used to match a regular expression against a string.

Method of

String

Syntax

match(regexp)

Parameters

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

Description

If you want to execute a global match, or a case insensitive match, include the g (for global) and i (for ignore case) flags in the regular expression. These can be included separately or together. The following two examples below show how to use these flags with match.

Note

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

Examples

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

str = "For more information, see Chapter 3.4.5.1";
re = /(chapter \d+(\.\d)*)/i;
found = str.match(re);
This returns the array containing Chapter 3.4.5.1,Chapter 3.4.5.1,.1

'Chapter 3.4.5.1' is the first match and the first value remembered from (Chapter \d+(\.\d)*).

'.1' is the second value remembered from (\.\d).

Example 2. The following example demonstrates the use of the global and ignore case flags with match.

str = "abcDdcba"; 
newArray = str.match(/d/gi);
The returned array contains D, d.

replace

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

Method of

String

Syntax

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. This string can include the RegExp properties $1, ..., $9, lastMatch, lastParen, leftContext, and rightContext.

Description

This 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, or a case insensitive search, include the g (for global) and i (for ignore case) flags in the regular expression. These can be included separately or together. The following two examples below show how to use these flags with replace.

Examples

Example 1. In the following example, the regular expression includes the global and ignore case flags which permits replace to replace each occurrence of 'apples' in the string with 'oranges.'

re = /apples/gi;
str = "Apples are round, and apples are juicy.";
newstr=str.replace(re, "oranges");
This prints "oranges are round, and oranges are juicy."

Example 2. In the following example, the regular expression is defined in replace and includes the ignore case flag.

str = "Twas the night before Xmas...";
newstr=str.replace(/xmas/i, "Christmas");
This prints "Twas the night before Christmas..."

Example 3. The following script switches the words in the string. For the replacement text, the script uses the values of the $1 and $2 properties.

re = /(\w+)\s(\w+)/;
str = "John Smith";
newstr = str.replace(re, "$2, $1");
This prints "Smith, John".

search

Executes the search for a match between a regular expression and this String object.

Method of

String

Syntax

search(regexp)

Parameters

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

Description

If successful, search returns the index of the regular expression inside the string. Otherwise, it returns -1.

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).

Example

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

function testinput(re, str){
   if (str.search(re) != -1)
      midstring = " contains ";
   else
      midstring = " does not contain ";
   print (str + midstring + re.source);
}

slice

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

Method of

String

Syntax

slice(beginslice,endSlice)

Parameters

beginSlice
The zero-based index at which to begin extraction.

endSlice
(Optional) The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string.

Description

slice extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string.

slice extracts up to but not including endSlice. string.slice(1,4) extracts the second character through the fourth character (characters indexed 1, 2, and 3).

As a negative index, endSlice indicates an offset from the end of the string. string.slice(2,-1) extracts the third character through the second to last character in the string.

Example

The following example uses slice to create a new string.

str1="The morning is upon us. "
str2=str1.slice(3,-5)
This writes:

morning is upon

small

Creates an HTML SMALL tag.

Method of

String

Syntax

small()

Parameters

None

Examples

var worldString="Hello, world"
worldString.small()
The previous example produces the following output:

<SMALL>Hello, world</SMALL>

See also

String.big, String.fontsize

split

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

Method of

String

Syntax

split(separator, limit)

Parameters

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

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

Description

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

Split has the following additions:

Examples

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

function splitString (stringToSplit,separator) {
   arrayOfStrings = stringToSplit.split(separator)
   print ('The original string is: "' + stringToSplit + '"')
   print ('The separator is: "' + separator + '"')
   print ("The array has " + arrayOfStrings.length + " elements: ")
   for (var i=0; i < arrayOfStrings.length; i++) {
      print (arrayOfStrings[i] + " / ")
   }
}
var tempestString="Oh brave new world that has such people in it."
var monthString="Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
var space=" "
var comma=","
splitString(tempestString,space)
splitString(tempestString)
splitString(monthString,comma)
This example produces the following output:

The original string is: "Oh brave new world that has such people in it."
The separator is: " "
The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it. /
The original string is: "Oh brave new world that has such people in it."
The separator is: "undefined"
The array has 1 elements: Oh brave new world that has such people in it. /
The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
The separator is: ","
The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec /
Example 2. Consider the following script:

version(120)
str="She sells seashells \nby the\n seashore"
str.split(" ")
Using version(120), this script produces

"She", "sells", "seashells", "by", "the", "seashore"
Without version(120), 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.

names = "Harry  Trump  ;Fred Barney; Helen   Rigby ;  Bill Abel ;Chris Hand ";
re = /\s*;\s*/;
nameList = names.split (re);
nameList contains the resulting array.

Harry Trump,Fred Barney,Helen Rigby,Bill Abel,Chris Hand

Example 4. In the following example, split looks for 0 or more spaces in a string and returns the first 3 splits that it finds.

version(120)
myVar = " Hello World. How are you doing? ";
myVar.split(" ", 3);
This script displays the following:

["Hello", "World.", "How"]

See also

String.charAt, String.indexOf, String.lastIndexOf

strike

Creates an HTML STRIKE tag.

Method of

String

Syntax

strike()

Parameters

None

Examples

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

var worldString="Hello, world"
worldString.strike()
The previous example produces the following output:

<STRIKE>Hello, world</STRIKE>

See also

String.blink, String.bold, String.italics

sub

Creates an HTML SUB tag.

Method of

String

Syntax

sub()

Parameters

None

Examples

The following example uses the sub and sup methods to format a string:

var subText="subscript"
"This is what a " + subText.sub() + " looks like."
The previous example produces the following output:

This is what a <SUB>subscript</SUB> looks like.

See also

String.sup

substr

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

Method of

String

Syntax

substr(start, length)

Parameters

start
Location at which to begin extracting characters.

length
(Optional) The number of characters to extract

Description

start 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

Consider the following script:

str = "abcdefghij"
"(1,2): ", str.substr(1,2)
"(-2,2): ", str.substr(-2,2)
"(1): ", str.substr(1)
"(-20, 2): ", str.substr(1,20)
"(20, 2): ", str.substr(20,2)
This script displays:

(1,2): bc
(-2,2): ij
(1): bcdefghij
(-20, 2): bcdefghij
(20, 2):

See also

substring

substring

Returns a subset of a String object.

Method of

String

Syntax

substring(indexA, indexB)

Parameters

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

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

Description

substring extracts characters from indexA up to but not including indexB. In particular:

Examples

Example 1. The following example uses substring to display characters from the string "Netscape":

var anyString="Netscape"
//Displays "Net"
anyString.substring(0,3)
anyString.substring(3,0)
//Displays "cap"
anyString.substring(4,7)
anyString.substring(7,4)
//Displays "Netscap"
anyString.substring(0,7)
//Displays "Netscape"
anyString.substring(0,8)
anyString.substring(0,10)
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".

function replaceString(oldS,newS,fullS) {
// Replaces oldS with newS in the string fullS
   for (var i=0; i<fullS.length; i++) {
      if (fullS.substring(i,i+oldS.length) == oldS) {
         fullS = fullS.substring(0,i)+newS+fullS.substring(i+oldS.length,fullS.length)
      }
   }
   return fullS
}
replaceString("World","Web","Brave New World")

See also

substr

sup

Creates an HTML SUP tag.

Method of

String

Syntax

sup()

Parameters

None

Examples

var superText="superscript"
"This is what a " + superText.sup() + " looks like."
The previous example produces the following output:

This is what a <SUP>superscript</SUP> looks like.

See also

String.sub

toLowerCase

Returns the calling string value converted to lowercase.

Method of

String

Syntax

toLowerCase()

Parameters

None

Description

The toLowerCase method returns the value of the string converted to lowercase. toLowerCase does not affect the value of the string itself.

Examples

The following example displays the lowercase string "alphabet":

var upperText="ALPHABET"
upperText.toLowerCase()

See also

String.toUpperCase

toUpperCase

Returns the calling string value converted to uppercase.

Method of

String

Syntax

toUpperCase()

Parameters

None

Description

The toUpperCase method returns the value of the string converted to uppercase. toUpperCase does not affect the value of the string itself.

Examples

The following example displays the string "ALPHABET":

var lowerText="alphabet"
lowerText.toUpperCase()

See also

String.toLowerCase


[Contents]

Last Updated: 10/31/97 12:30:31


Copyright © 1997 Netscape Communications Corporation