JavaScript tutorial:
substr method

 

Applies to: String Object

The substr method returns a substring beginning at a specified location and having a specified length.

Syntax

stringvar.substr(start [, length ])

The substr method syntax has these parts:

Part

Description

stringvar

Required. A string literal or String object from which the substring is extracted.

start

Required. The starting position of the desired substring. The index of the first character in the string is zero.

length

Optional. The number of characters to include in the returned substring.

Example

If length is zero or negative, an empty string is returned. If not specified, the substring continues to the end of stringvar.

The following example illustrates the use of the substr method:

function copySpecificString(str,begin,length)
{
return(str.substr(begin,length));
}
document.write(copySpecificString("Java script is fun let start learning","0", "19"));

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

See also: String Object methods, String Object Properties, substring method