substring

Returns a subset of a String object.

Applies to

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

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

var anyString="Netscape"
//Displays "Net"
Console.Write(anyString.substring(0,3))
Console.Write(anyString.substring(3,0))
//Displays "cap"
Console.Write(anyString.substring(4,7))
Console.Write(anyString.substring(7,4))
//Displays "Netscap"
Console.Write(anyString.substring(0,7))
//Displays "Netscape"
Console.Write(anyString.substring(0,8))
Console.Write(anyString.substring(0,10))

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