Javascript String Objects


String Object

Methods string.method   Properties
anchor Method
big Method
blink Method
bold Method
charAt Method
charCodeAt Method
concat Method
fixed Method
fontcolor Method
fontsize Method
fromCharCode Method
indexOf Method
italics Method
lastIndexOf Method
link Method
match Method
replace Method
search Method
slice Method
small Method
split Method
strike Method
sub Method
substr Method
substring Method
sup Method
toLowerCase Method
toUpperCase Method
 
Members of String.prototype

constructor Property

Nonmembers of String.prototype

length Property
prototype Property


anchor Method
Description

Places an HTML anchor with a NAME attribute around specified text in the object.

Syntax

strVariable.anchor(anchorstring)
"String Literal".anchor(anchorstring)

The anchorstring argument is text you want to place in the NAME attribute of an HTML anchor. --Bookmark on your web page

Remarks

Call the anchor method to create a named anchor out of a String object. The following example demonstrates how the anchor method accomplishes this:

var strVariable = "This is an anchor" ;
strVariable = strVariable.anchor("Anchor1");

The value of strVariable after the last statement is:

<A NAME="Anchor1">This is an anchor</A>

No checking is done to see if the tag has already been applied to the string.

Copy this sample code to test yourself. I tested it on IE 5 and Netscape 4.7. They both work!

<Script Language=JavaScript>
var strVariable = "This is an anchor" ;
strVariable = strVariable.anchor("Anchor1");
document.write(strVariable);
</Script>
<p>
<Pre>

















</pre>
<a href=#Anchor1>Back to Top</a>


big Method
Description

Places HTML <BIG> tags around text in a String object.

Syntax

strVariable.big( )
"String Literal".big( )

Remarks

The example that follows shows how the big method works:

var strVariable = "This is a string object";
strVariable = strVariable.big( );

The value of strVariable after the last statement is:

<BIG>This is a string object</BIG>

blink Method
Description

Places HTML <BLINK> tags around text in a String object.

Syntax

strVariable.blink( )
"String Literal".blink( )

Remarks

The following example demonstrates how the blink method works:

var strVariable = "This is a string object";
strVariable = strVariable.blink( );

The value of strVariable after the last statement is:

<BLINK>This is a string object</BLINK>

The <BLINK> tag is not supported in Microsoft Internet Explorer.


bold Method

Description

Places HTML <B> tags around text in a String object.

Syntax

strVariable.bold( )
"String Literal".bold( )

Remarks

The following example demonstrates how the bold method works:

var strVariable = "This is a string object";
strVariable = strVariable.bold( );

The value of strVariable after the last statement is:

<B>This is a string object</B>

charAt Method

Description

Returns the character at the specified index.

Syntax

strVariable.charAt(index)
"String Literal".charAt(index)

The index argument is the zero-based index of the desired character. Valid values are between 0 and the length of the string minus 1.

Remarks

The charAt method returns a character value equal to the character at the specified index. The first character in a string is at index 0, the second is at index 1, and so forth. Values of index out of valid range return undefined.

The following example illustrates the use of the charAt method:

function charAtTest(n)
{
  var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var s;
  s = str.charAt(n - 1);
  return(s);
}


charCodeAt Method

Description

Returns the Unicode encoding of the specified character.

Syntax

stringObj.charCodeAt(index)

The charCodeAt method syntax has these parts:

Part Description
stringObj Required. A String object or literal.
index Required. The zero-based index of the specified character.
Remarks

If there is no character at the specified index, NaN is returned.

The following example illustrates the use of the charCodeAt method:

function charCodeAtTest(n)
{
  var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var s;
  s = str.charCodeAt(n - 1);
  // Return Unicode character code.
  return(s);
}

concat Method (String)
Description

Returns a String object containing the concatenation of two supplied strings.

Syntax

string1.concat(string2)

The concat method syntax has these parts:

Part Description
string1 Required. The String object or literal to concatenate with string2.
string2 Required. A String object or literal to concatenate to the end of string1.
Remarks

The result of the concat method is equivalent to: result = string1 + string2.

The following example illustrates the use of the concat method:

function concatDemo()
{
  var str1 = "ABCDEFGHIJKLM"
  var str2 = "NOPQRSTUVWXYZ";
  var s = str1.concat(str2);
  // Return concatenated string.
  return(s);
}

fixed Method

Description

Places HTML <TT> tags around text in a String object.

Syntax

strVariable.fixed( )
"String Literal".fixed( )

Remarks

The following example demonstrates how the fixed method works:

var strVariable = "This is a string object";
strVariable = strVariable.fixed( );

The value of strVariable after the last statement is:

<TT>This is a string object</TT>


fontcolor Method

Description

Places an HTML <FONT> tag with the COLOR attribute around the text in a String object.

Syntax

strVariable.fontcolor(colorval)
"String Literal".fontcolor(colorval)

The colorval argument is a string containing a color value. This can either be the hexadecimal value for a color, or the predefined name for a color.

Remarks

The following example demonstrates the fontcolor method:

var strVariable = "This is a string";
strVariable = strVariable.fontcolor("red");

The value of strVariable after the last statement is:

<FONT COLOR="RED">This is a string</FONT>

Valid predefined color names depend on your JScript host (browser, server, and so forth). They may also vary from version to version of your host. Check your host documentation for more information.


fontsize Method

Description

Places an HTML <FONT> tag with the SIZE attribute around the text in a String object.

Syntax

strVariable.fontsize(intSize)
"String Literal".fontsize(intSize)

The intSize argument is an integer value that determines the size of the text.

Remarks

The following example demonstrates the fontsize method:

var strVariable = "This is a string";
strVariable = strVariable.fontsize(-1);

The value of strVariable after the last statement is:

<FONT SIZE="-1">This is a string</FONT>

fromCharCode Method

Description

Returns a string from a number of Unicode character values.

Syntax

String.fromCharCode(code1, code2, ..., coden)

The code argument is the series of Unicode character values to convert into a string.

Remarks

A String object need not be created before calling fromCharCode.

In the following example, test contains the string "plain":

var test = String.fromCharCode(112, 108, 97, 105, 110);
a b c d e f g h i j k l m n o p q r s t u v x w y z
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
A B C D E F G H I J K L M N O P Q R S T U V X W Y Z
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

indexOf Method

Description

Returns the character position where the first occurrence a substring occurs within a String object.

Syntax

strVariable.indexOf(substring, startindex)
"String Literal".indexOf(substring, startindex)

The indexOf method syntax has these arguments:

Part Description
substring The substring to search for within the String object.
startindex An optional integer value specifying the index to begin searching within the String object. If omitted, searching begins at the beginning of the string.
Remarks

The indexOf method returns an integer value indicating the beginning of the substring within the String object. If the substring is not found, a -1 is returned.

If startindex is negative, startindex is treated as zero. If it is larger than the greatest character position index, it is treated as the largest possible index.

Searching is performed from left to right. Otherwise, this method is identical to lastIndexOf.

The following example illustrates the use of the indexOf method:

function IndexDemo(str2)
{
  var str1 = "BABEBIBOBUBABEBIBOBU"
  var s = str1.indexOf(str2);
  return(s);
}

italics Method
Description

Places HTML <I> tags around text in a String object.

Syntax

strVariable.italics( )
"String Literal".italics( )

Remarks

The following example demonstrates how the italics method works:

var strVariable = "This is a string";
strVariable = strVariable.italics( );

The value of strVariable after the last statement is:

<I>This is a string</I>

lastIndexOf Method
Description

Returns the last occurrence of a substring within a String object.

Syntax

strVariable.lastIndexOf(substring, startindex)
"String Literal".lastIndexOf(substring, startindex)

The lastIndexOf method syntax has these arguments:

Part Description
substring The substring to search for within the String object.
startindex An optional integer value specifying the index to begin searching within the String object. If omitted, searching begins at the end of the string.
Remarks

The lastIndexOf method returns an integer value indicating the beginning of the substring within the String object. If the substring is not found, a -1 is returned.

If startindex is negative, startindex is treated as zero. If it is larger than the greatest character position index, it is treated as the largest possible index.

Searching is performed right to left. Otherwise, this method is identical to indexOf.

The following example illustrates the use of the lastIndexOf method:

function lastIndexDemo(str2)
{
  var str1 = "BABEBIBOBUBABEBIBOBU"
  var s = str1.lastIndexOf(str2);
  return(s);
}

link Method
Description

Places an HTML anchor with an HREF attribute around the text in a String object.

Syntax

strVariable.link(linkstring)
"String Literal".link(linkstring)

The linkstring argument is the text that you want to place in the HREF attribute of the HTML anchor.

Remarks

Call the link method to create a hyperlink out of a String object. The following is an example of how the method accomplishes this:

var strVariable = "This is a hyperlink";
strVariable = strVariable.link("http://www.shop4all.com");

The value of strVariable after the last statement is:

<A HREF="http://www.shop4all.com">This is a hyperlink</A>

match Method
Description

Returns, as an array, the results of a search on a string using a supplied Regular Expression object.

Syntax

stringObj.match(rgExp)

The match method syntax has these parts:

Part Description
stringObj Required. The String object or literal on which to perform the search.
rgExp Required. The regular expression to use in the search.
Remarks

The match method, which behaves like the exec method, returns an array of values. Element zero of the array contains the last matched characters. Elements 1...n contain matches to any parenthesized substrings in the regular expression.

The method updates the contents of the RegExp object.

The following example illustrates the use of the match method:

function MatchDemo()
{
  var r, re;
  var s = "The quick brown fox jumped over the lazy yellow dog.";
  re = /fox/i;
  r = s.match(re);
  return(r);
}

replace Method
Description

Returns a copy of a string with text replaced using a regular expression.

Syntax

stringObj.replace(rgExp, replaceText)

The replace method syntax has these parts:

Part Description
stringObj Required. The String object or literal on which to perform the replace. This object is not modified by the replace method.
rgExp Required. A Regular Expression object describing what to search for.
replaceText Required. A String object or literal containing the text to replace for every successful match of rgExp in stringObj.
Remarks

The result of the replace method is a copy of stringObj after all replacements have been made.

The method updates the contents of the RegExp object.

The following example illustrates the use of the replace method:

function ReplaceDemo()
{
  var r, re;
  var s = "The quick brown fox jumped over the lazy yellow dog.";
  re = /fox/i;
  r = s.replace(re, "pig");
  return(r);
}

In addition, the replace method can also replace subexpressions in the pattern. The following example swaps each pair of words in the string:

function ReplaceDemo()
{
  var r, re;
  var s = "The quick brown fox jumped over the lazy yellow dog.";
  re = /(\S+)(\s+)(\S+)/g;
  r = s.replace(re, "$3$2$1");	// Swap each pair of words.
  return(r);
}

search Method
Description

Returns the position of the first substring match in a regular expression search.

Syntax

stringObj.search(rgexp)

The search method syntax has these parts:

Part Description
stringObj Required. The String object or literal to search.
rgexp Required. A Regular Expression object containing the pattern to search for.
Remarks

The search method indicates if a match is present or not. If a match is found, the search method returns an integer value that indicates the offset from the beginning of the string where the match occurred. If no match is found, it returns -1. To get further information, use the match method.

The following example illustrates the use of the search method:

function SearchDemo()
{
  var r, re;
  var s = "The quick brown fox jumped over the lazy yellow dog.";
  re = /fox/i;
  r = s.search(re);
  return(r);
}

slice Method (String)
Description

Returns a section of a string.

Syntax

stringObj.slice(start, [end])

The slice method syntax has these parts:

Part Description
stringObj Required. A String object or literal.
start Required. The zero-based index of the beginning of the specified portion of stringObj.
end Optional. The zero-based index of the end of the specified portion of stringObj.
Remarks

The slice method returns a String object containing the specified portion of stringObj.

If negative, end indicates an offset from the end of stringObj. In addition, it is not zero-based. If omitted, extraction continues to the end of stringObj.

In the example that follows, the two uses of the slice method return the same thing. Negative one in the second example points to the last character in str1 as the ending point:

str1.slice(0)
str2.slice(0,-1)

small Method
Description

Places HTML <SMALL> tags around text in a String object.

Syntax

strVariable.small( )
"String Literal".small( )

Remarks

The example that follows demonstrates how the small method works:

var strVariable = "This is a string";
strVariable = strVariable.small( );

The value of strVariable after the last statement is:

<SMALL>This is a string</SMALL>

split Method
Description

Returns the array of strings that results when a string is separated into substrings.

Syntax

stringObj.split(str)

The split method syntax has these parts:

Part Description
stringObj Required. The String object or literal to be split. This object is not modified by the split method.
str Required. A string or Regular Expression object describing what character is used to define where the splits take place.
Remarks

The result of the split method is an array of strings split at each point where str occurred in stingObj.

The following example illustrates the use of the split method:

function SplitDemo()
{
  var s, ss;
  var s = "The quick brown fox jumped over the lazy yellow dog.";
  // Split at each space character.
  ss = s.split(" ");
  return(ss);
}

strike Method
Description

Places HTML <STRIKE> tags around text in a String object.

Syntax

strVariable.strike( )
"String Literal".strike( )

Remarks

The following example demonstrates how the strike method works:

var strVariable = "This is a string object";
strVariable = strVariable.strike( );

The value of strVariable after the last statement is:

<STRIKE>This is a string object</STRIKE>

sub Method
Description

Places HTML <SUB> tags around text in a String object.

Syntax

strVariable.sub( )
"String Literal".sub( )

Remarks

The following example demonstrates how the sub method works:

var strVariable = "This is a string object"
strVariable = strVariable.sub( );

The value of strVariable after the last statement is:

<SUB>This is a string object</SUB>

substr Method
Description

Returns a substring beginning at a specified location and having a specified length.

Syntax

stringvar.substr(start [, length ])

The substr method syntax has these parts:

Part Description
stringvar Required. A string literal or String object from which the substring is extracted.
start Required. The starting position of the desired substring. The index of the first character in the string is zero.
length Optional. The number of characters to include in the returned substring.
Remarks

If length is zero or negative, an empty string is returned. If not specified, the substring continues to the end of stringvar.

The following example illustrates the use of the substr method:

function SubstrDemo()
{
  var s, ss;
  var s = "The quick brown fox jumped over the lazy yellow dog.";
  ss = s.substr(16, 3);
  // Returns "fox".
  return(ss);
}

substring Method
Description

Returns the substring at the specified location within a String object.

Syntax

strVariable.substring(start, end)
"String Literal".substring(start, end)

The substring method syntax has these arguments:

Part Description
start The zero-based index indicating the beginning of the substring.
end The zero-based index indicating the end of the substring.
Remarks

The substring method returns a String object containing the substring derived from the original object.

The substring method uses the lower of start and end as the beginning point of the substring. For example, strvar.substring(0, 3) and strvar.substring(3, 0) return the same substring.

The only exception to this is for negative parameters. If the first parameter is less than zero, it is treated as zero. If the second parameter is negative, it is set to the value of the first parameter.

The length of the substring is equal to the absolute value of the difference between start and end. For example, the length of the substring returned in strvar.substring(0, 3) and strvar.substring(3, 0) is three.

Finally, start and end can be strings. If so, these strings are coerced into integers if possible. If not, the value of the parameter is treated as zero.

The following example illustrates the use of the substring method:

function SubstringDemo()
{
  var s, ss;
  var s = "The quick brown fox jumped over the lazy yellow dog.";
  ss = s.substring(16, 19);
  return(ss);
}

sup Method
Description

Places HTML <SUP> tags around text in a String object.

Syntax

strVariable.sup( )
"String Literal".sup( )

Remarks

The following example demonstrates how the sup method works:

var strVariable = "This is a string object";
strVariable = strVariable.sup( );

The value of strVariable after the last statement is:

<SUP>This is a string object</SUP>

toLowerCase Method
Description

Returns a string where all alphabetic characters have been converted to lowercase.

Syntax

strVariable.toLowerCase( )
"String Literal".toLowerCase( )

Remarks

The toLowerCase method has no effect on nonalphabetic characters.

The following example demonstrates the effects of the toLowerCase method:

var strVariable = "This is a STRING object";
strVariable = strVariable.toLowerCase( );

The value of strVariable after the last statement is:

this is a string object

toUpperCase Method
Description

Returns a string where all alphabetic characters have been converted to uppercase.

Syntax

strVariable.toUpperCase( )
"String Literal".toUpperCase( )

Remarks

The toUpperCase method has no effect on nonalphabetic characters.

The following example demonstrates the effects of the toUpperCase method:

var strVariable = "This is a STRING object";
strVariable = strVariable.toUpperCase( );

The value of strVariable after the last statement is:

THIS IS A STRING OBJECT

constructor Property
Description

Specifies the function that creates an object.

Syntax

object.constructor

The required object argument is the name of an object or function.

Remarks

The constructor property is a member of the prototype of every object that has a prototype. This includes all intrinsic JScript objects except the Global and Math objects. The constructor property contains a reference to the function that constructs instances of that particular object. For example:

x = new String("Hi");
if (x.constructor == String)
   	// Do something (the condition will be true).

or

function MyFunc {
	// Body of function.
}

y = new MyFunc;
if (y.constructor == MyFunc)
   	// Do something (the condition will be true).

length Property (String)
Description

Returns the length of a String object.

Syntax

strVariable.length
"String Literal".length

Remarks

The length property contains an integer that indicates the number of characters in the String object. The last character in the String object has an index of length - 1.


prototype Property
Description

Returns a reference to the prototype for a class of objects.

Syntax

objectname.prototype

The objectname argument is the name of an object.

Remarks

Use the prototype property to provide a base set of functionality to a class of objects. New instances of an object "inherit" the behavior of the prototype assigned to that object.

For example, say you want to add a method to the Array object that returns the value of the largest element of the array. To do this, declare the function, add it to Array.prototype, and then use it.

function array_max( )
{
  var i, max = this[0];
  for (i = 1; i < this.length; i++)
  {
     if (max < this[i])
	     max = this[i];
  }
  return max;
}
Array.prototype.max = array_max;
var x = new Array(1, 2, 3, 4, 5, 6);
var y = x.max( );

After this code is executed, y contains the largest value in the array x, or 6.

All intrinsic JScript objects have a prototype property that is read-only. Functionality may be added to the prototype, as in the example, but the object may not be assigned a different prototype. However, user-defined objects may be assigned a new prototype.

The method and property lists for each intrinsic object in this language reference indicate which ones are part of the object's prototype, and which are not.



eval Method

Description

Evaluates JScript code and executes it.

Syntax

eval(codestring)

The codestring argument is a String object that contains valid JScript code. This string is parsed by the JScript parser and executed.

Remarks

The eval function allows dynamic execution of JScript source code. For example, the following code creates a new variable mydate that contains a Date object:

eval("var mydate = new Date();");

The code passed to the eval method is executed in the same context as the call to the eval method.