String methods

Provides a reference for string methods.

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

Table 1. String methods
Syntax Effect
string.substring(start [ , end ] )

Returns the substring of string starting at the index start and ending at the index end-1. If end is omitted, the tail of string is returned.

Examples:

"0123456".substring(0, 3) –> "012"

"0123456".substring(2, 4) –> "23"

"0123456".substring(2) –> "23456"

string.charAt(index)

Returns a one-character string containing the character at the specified index of string. If index is out of range, an empty string is returned.

Examples:

"abcdef".charAt(0) –> "a"

"abcdef".charAt(3) –> "d"

"abcdef".charAt(100) –> ""

string.charCodeAt(index)

Returns the ASCII code of the character at the specified index of string. Ifindex is out of range, returns NaN.

Examples:

"abcdef".charCodeAt(0) –> 97

"abcdef".charCodeAt(3) –> 100

"abcdef".charCodeAt(100) –> NaN

string.indexOf(substring [ , index ] )

Returns the index in string of the first occurrence of substring. The string is searched starting at index. If index is omitted, string is searched from the beginning. This method returns -1 if substring is not found.

Examples:

"abcdabcd".indexOf("bc") –> 1

"abcdabcd".indexOf("bc", 1) –> 1

"abcdabcd".indexOf("bc", 2) –> 5

"abcdabcd".indexOf("bc", 10) –> -1

"abcdabcd".indexOf("foo") –> -1

"abcdabcd".indexOf("BC") –> -1

string.lastIndexOf(substring [ , index ] )

Returns the index in string of the last occurrence of substring, when string is searched backwards, starting at index. If index is omitted, string is searched from the end. This method returns -1 if substring is not found.

Examples:

"abcdabcd".lastIndexOf("bc") –> 5

"abcdabcd".lastIndexOf("bc", 5) –> 5

"abcdabcd".lastIndexOf("bc", 4) –> 1

"abcdabcd".lastIndexOf("bc", 0) –> -1

"abcdabcd".lastIndexOf("foo") –> -1

"abcdabcd".lastIndexOf("BC") –> -1

string.toLowerCase()

Returns string converted to lowercase.

Example:

"Hello, World".toLowerCase() "hello, world"
string.toUpperCase()

string.toUpperCase() Returns string converted to uppercase.

Example:

"Hello, World".toUpperCase() "HELLO, WORLD"
string.split(separator)

Returns an array of strings containing the substrings of string that are separated by separator. See also the array method join.

Examples:

"first name,last name,age".split(",") -> an array a such that .length is 3, a[0] is "first name", a[1] is "last name", and a[2] is "age".

If string does not contain separator, an array with one element containing the whole string is returned.

Example:

"hello".split(",") –> an array a such that a.length is 1 and a[0] is "hello",

string.toString() Returns the string itself.