Latest web development tutorials

JavaScript slice () method

String Object Reference JavaScript String Object

Examples

Extract pieces of the string:

var str="Hello world!";
var n=str.slice(1,5);

n output:

ello

try it"

Definition and Usage

slice () method can extract a portion of the string and returns a new string is extracted portions.

Use start and end parameter to specify a string extraction portion.

The first character in the string position is 0, the second character position is 1, and so on.

Tip: If it is negative, then the parameter is specified from the end of the string since the beginning position.That is, the last character of -1 means that the string, -2 means the second last character, and so on.


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support slice () method.


grammar

string.slice( start , end )

Parameter Value

参数 描述
start 必须. 要抽取的片断的起始下标。第一个字符位置为 0
end 可选。 紧接着要抽取的片段的结尾的下标。若未指定此参数,则要提取的子串包括 start 到原字符串结尾的字符串。如果该参数是负数,那么它规定的是从字符串的尾部开始算起的位置。

return value

类型 描述
String The extracted part of the string

technical details

JavaScript version: 1.0


More examples

Examples

Extract all strings:

var str="Hello world!";
var n=str.slice(0);

Examples of the above output:

Hello world!

try it"

Examples

String fragment extracted from the third position of the string:

var str="Hello world!";
var n=str.slice(3);

Examples of the above output:

lo world!

try it"

Examples

8 string fragment extracted from the third position of the string:

var str="Hello world!";
var n=str.slice(3,8);

Examples of the above output:

lo wo

try it"

Examples

Extract only the first one character:

var str="Hello world!";
var n=str.slice(0,1);

Examples of the above output:

H

try it"

Examples

Extraction last character:

var str="Hello world!";
var n=str.slice(-1);

Examples of the above output:

!

try it"


String Object Reference JavaScript String Object