[Contents] [Previous] [Next] [Last]

Chapter 6
The String Object

This section describes the new methods for strings. * indicates a change to an existing method.

charCodeAt

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

Syntax

string.charCodeAt([index])

Parameters

string is any string.

index, an optional argument, is any integer from 0 to string.length-1, or a property of an existing object. The default value is 0.

Method of

String object

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 the ISO-Latin-1 codeset value of 65.

"ABC".charCodeAt(0)

concat

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

Syntax

string1.concat(string2)

Parameters

string1 is the first string.

string2 is the second string.

Method of

String object

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.

<SCRIPT LANGUAGE="JavaScript1.2">
str1="The morning is upon us. "
str2="The sun is bright."
str3=str1.concat(str2)
document.write(str3)
</SCRIPT>
This writes:

The morning is upon us. The sun is bright.

fromCharCode

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

Syntax

String.fromCharCode(num1, num2, ..., numn)

Parameters

numn is a sequence of numbers that are ISO-Latin-1 codeset values.

Method of

String object

Description

This method returns a string and not a String object.

Examples

Example 1.: The following example returns the string "ABC".

String.fromCharCode(65,66,67)
Example 2. : The which property of the KeyDown, KeyPress, and KeyUp events contains the ASCII value of the key pressed at the time the event occurred. If you want to get the actual letter, number, or symbol of the key, you can use fromCharCode. The following example returns the letter, number, or symbol of the KeyPress event's which property.

String.fromCharCode(KeyPress.which)

match

Core method. Used to match a regular expression against a string.

Syntax

string.match(regexp)

Parameters

string is any string.

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

Method of

String object

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 are executing a match simply to find true or false, use search or the regular expression test method.

Examples

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

<SCRIPT LANGUAGE="JavaScript1.2"> 
str = "For more information, see Chapter 3.4.5.1";
re = /(chapter \d+(\.\d)*)/i;  
found = str.match(re);  
document.write(found); 
</SCRIPT >
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.

<SCRIPT LANGUAGE="JavaScript1.2"> 
str = "abcDdcba"; 
newArray = str.match(/d/gi);  
document.write(newArray); 
</SCRIPT >
The returned array contains D, d.

replace

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

Syntax

string.replace(regexp, newSubStr)

Parameters

string is a string. This string can include the RegExp properties $1,..., $9, lastMatch, lastParen, leftContext, and rightContext.

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

newSubStr is the string to replace the string found with regexp.

Method of

String object

Description

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

<SCRIPT LANGUAGE="JavaScript1.2">
re = /apples/gi;
str = "Apples are round, and apples are juicy.";
newstr=str.replace(re, "oranges");
document.write(newstr)
</SCRIPT>
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.

<SCRIPT LANGUAGE="JavaScript1.2">
str = "Twas the night before Xmas...";
newstr=str.replace(/xmas/i, "Christmas");
document.write(newstr)
</SCRIPT>
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.

<SCRIPT LANGUAGE="JavaScript1.2">
re = /(\w+)\s(\w+)/;
str = "John Smith";
newstr = str.replace(re, "$2, $1");
document.write(newstr)
</SCRIPT>
This prints "Smith, John".

search

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

Syntax

string.search(regexp)

Parameters

string is any string.

regexp is the 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 ";
   document.write (str + midstring + re.source);
}

slice

Core method. Extracts a section of an string and returns a new string.

Syntax

string.slice(beginslice,[endSlice])

Parameters

string is a string.

beginSlice is the zero-based index at which to begin extraction.

endSlice is the zero-based index at which to end extraction.

Method of

String object

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.

Example

The following example uses slice to create a new string.

<SCRIPT LANGUAGE="JavaScript1.2">
str1="The morning is upon us. "
str2=str1.slice(3,-5)
document.write(str2)
</SCRIPT>
This writes:

morning is upon

split

Core method. split has the following additions:

Syntax

string.split([separator], [limit])

Parameters

string is any string.

separator specifies the character or regular expression to use for separating the string.

limit is an optional integer that specifies a limit on the number of splits to be found.

Method of

String object

Description

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.

If separator is a regular expression, any included parenthesis cause submatches to be included in the returned array.

Using the optional limit argument, you can avoid including trailing empty elements in the returned array.

Examples

Example 1.: Using LANGUAGE="JavaScript1.2", the following script produces

["She", "sells", "seashells", "by", "the", "seashore"]
<SCRIPT LANGUAGE="JavaScript1.2"> 
str="She sells    seashells \nby   the\n seashore"
document.write(str + "<BR>")
a=str.split(" ")
document.write(a)
</SCRIPT>
Without LANGUAGE="JavaScript1.2", the above script splits only on single space characters, producing

She,sells,,,,seashells, by,,,the ,seashore
Example 2.: In the following example, split looks for zero to many spaces followed by a semi-colon followed by zero to many spaces and, when found, removes them from the string. nameList is the array returned as a result of split.

<SCRIPT LANGUAGE="JavaScript1.2">
names = "Harry  Trump  ;Fred Barney; Helen   Rigby ;  Bill Abel ;Chris Hand ";
document.write (names + "<BR>" + "<BR>");
re = /\s*;\s*/;
nameList = names.split (re);
document.write(nameList);
</SCRIPT>
This prints two lines; the first line prints the original string, and the second line prints the resulting array.

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

["Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand"]

substr

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

Syntax

str.substr(start, [length])

Parameters

str is any string.

start is the location at which to begin extracting characters.

length, an optional argument, is the number of characters to extract.

Method of

String object

Description

start is a character index. The index of the first character is 0, and the index of the last character is str.length-1. substr begins extracting characters at start and collects length number of characters.

If start is positive and is longer than str.length-1, 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:

<SCRIPT LANGUAGE="JavaScript1.2">
str = "abcdefghij"
document.writeln("(1,2): ", str.substr(1,2))
document.writeln("(-2,2): ", str.substr(-2,2))
document.writeln("(1): ", str.substr(1))
document.writeln("(-20, 2): ", str.substr(1,20))
document.writeln("(20, 2): ", str.substr(20,2))
</SCRIPT>
This script displays:

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

substring

If you specify LANGUAGE="JavaScript1.2" in the script tag, substring(x,y) no longer swaps x and y.

Syntax

string.substring(indexA, [indexB])

Parameters

string is any string.

indexA is any integer from zero to stringName.length-1.

indexB, an optional argument, is any integer from zero to stringName.length.

Method of

String object

Description

substring behaves as follows:

Using LANGUAGE="JavaScript1.2" in the <SCRIPT> tag,

Without LANGUAGE="JavaScript1.2",

Example

Using LANGUAGE="JavaScript1.2", the following script produces a runtime error (out of memory).

<SCRIPT LANGUAGE="JavaScript1.2">
str="Netscape"
document.write(str.substring(0,3);
document.write(str.substring(3,0);
</SCRIPT>
Without LANGUAGE="JavaScript1.2", the above script prints

Net Net

In the second write, the index numbers are swapped.


[Contents] [Previous] [Next] [Last]

Last Updated: 10/22/97 11:48:06


Copyright 1997 Netscape Communications Corporation