Returns a subset of a String object.
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.
substring extracts characters from indexA up to but not including indexB. In particular:
If indexA is less than 0, indexA is treated as if it were 0.
If indexB is greater than stringName.length, indexB is treated as if it were stringName.length.
If indexB is omitted, substring extracts characters to the end of the string.
If indexA is greater than indexB, JavaScript returns a substring beginning with indexB and ending with indexA - 1.
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")