JavaScript tutorial:
substring method

 

Applies to: String Object

The substring method returns the substring at the specified location within a String object.

Syntax

strVariable.substring(start, end)
"String Literal".substring(start, end)

The substring method syntax has these arguments:

Part

Description

start

The zero-based index indicating the beginning of the substring.

end

The zero-based index indicating the end of the substring.

Return value

The substring method returns a string from specific start location to specific end of original string.

Example

The substring method returns a String object containing the substring derived from the original object.

The substring method uses the lower of start and end as the beginning point of the substring. For example, strvar.substring(0, 3) and strvar.substring(3, 0) return the same substring.

The only exception to this is for negative parameters. If the first parameter is less than zero, it is treated as zero. If the second parameter is negative, it is set to the value of the first parameter.

The length of the substring is equal to the absolute value of the difference between start and end. For example, the length of the substring returned in strvar.substring(0, 3) and strvar.substring(3, 0) is three.

Finally, start and end can be strings. If so, these strings are coerced into integers if possible. If not, the value of the parameter is treated as zero.

The following example illustrates the use of the substring method:
function copyString(Str,varStart, varEnd)
{
return(Str.substring(varStart,varEnd));
}
document.write(copyString("The world is not enough, Mr Bond","4","15"));

To run the code, paste it into JavaScript Editor, and click the Execute button.

See also: String Object methods, String Object properties, substr method