JavaScript substr()Method

String 对象参考手册JavaScript String Object

Examples

Extract the specified number of characters:

var str="Hello world!";
var n=str.substr(2,3)

nOutput:

llo

Try it Yourself »

Definition and Usage

The substr() method can extract from the string, starting from thestartindex, the specified number of characters.

Tip:The parameters of substr() specify the start position and length of the substring, so it can be used instead of substring() and slice().
In IE 4, the value of the parameter start is invalid. In this bug, start specifies the position of the 0th character. In later versions, this bug has been fixed.
ECMAScript has not standardized this method, so its use is deprecated.

Note:The substr() method does not change the original string.


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the substr() method


Syntax

string.substr(start,length)

Parameter Values

Parameter Description
start Required. The starting index of the substring to extract. Must be a numeric value. If it is a negative number, then this parameter declares the position counted from the end of the string. That is, -1 refers to the last character in the string, -2 refers to the second-to-last character, and so on.
length Optional. The number of characters in the substring. Must be a numeric value. If this parameter is omitted, then the substring from the start position of stringObject to the end is returned.

Return Value

Type Description
String A new string containing the extracted part of the text

Technical Details

JavaScript Version: 1.0


More Examples

Examples

In this example, we will use substr() to extract some characters from the second position of the string:

var str="Hello world!";
var n=str.substr(2)

nOutput:

llo world!

Try it Yourself »


String 对象参考手册JavaScript String Object

Other Extensions