[Chapter 21] Reference: String.substring()
Author: David Flanagan
Date: Fri Aug 29 11:20:08 1997

#

| Chapter 21 JavaScript Reference |

# String.substring() Method

## Name

String.substring() Method---return a substring of a string

## Availability

Navigator 2.0, Internet Explorer 3.0

## Synopsis

    string.substring(from, to)

### Arguments

`from`

  An integer that specifies the position within `string` of the first character of the desired substring. `from` must be between 0 and `string``.length`-1.

`to`

  An optional integer that is one greater than the position within `string` of the last character of the desired substring. `to` must be between 1 and `string``.length`.

### Returns

A new string, of length `to-from,` which contains a substring of `string`. The new string contains characters copied from positions `from` to `to-1` of `string`.

## Description

`String.substring()` returns the specified substring of `string.` If `from` equals `to`, `String.substring()` returns an empty (length 0) string. If `from` is greater than `to`, this method first swaps the two arguments before proceeding.

## Usage

`String.substring()` can be a confusing function to use. It is important to remember that the character at position `from` is included in the substring, but that the character at position `to` is not included in the substring. One notable feature of assigning the arguments this way is that the length of the returned substring is always equal to `to-from.`

Often it is more convenient to extract a substring of a string by specifying the start character and the desired length of the substring. You can do this with a function like the following:

    function substring2(string, start, length) {
        return string.substring(start, start+length);
    }

## See Also

"String", "String.charAt()", "String.indexOf()", "String.lastIndexOf()"

String.sub() |  | String.sup()