Latest web development tutorials

JavaScript substr () method

String Object Reference JavaScript String Object

Examples

Extracting a specified number of characters:

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

n output:

llo

try it"

Definition and Usage

substr () method can be extracted from the next mark the beginning of a specified number of characters in a string.

Tip: substr () parameter specifies the substring starting position and length, so it can replace substring () and slice () to use.
In IE 4, the start value of the parameter is invalid. In this BUG in, start position is specified in the 0th character. In later versions, this BUG has been fixed.
ECMAscript not the method is standardized, so opposed to using it.

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


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support substr () method


grammar

string.substr( start , length )

Parameter Value

参数 描述
start 必需。要抽取的子串的起始下标。必须是数值。如果是负数,那么该参数声明从字符串的尾部开始算起的位置。也就是说,-1 指字符串中最后一个字符,-2 指倒数第二个字符,以此类推。
length 可选。子串中的字符数。必须是数值。如果省略了该参数,那么返回从 stringObject 的开始位置到结尾的字串。

return value

类型 描述
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 a string in the second position:

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

n output:

llo world!

try it"


String Object Reference JavaScript String Object