JavaScript String slice()Method

String 对象参考手册JavaScript String Object

Example

Extract a portion of the string:

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

nOutput result:

ello

Try it Yourself »

Definition and Usage

The slice(start, end) method extracts a part of a string and returns the extracted part as a new string.

Use the start (inclusive) and end (exclusive) parameters to specify the part of the string to extract.

In the start parameter, the first character in the string is at position 0, the second character at position 1, and so on. If it is a negative number, it indicates how many characters to extract from the tail. slice(-2) extracts the second-to-last element to the last element (including the last element) from the original array.

If the end parameter is negative, -1 refers to the position of the last character in the string, -2 refers to the second-to-last character, and so on.


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the slice() method.


Syntax

string.slice(start,end)

Parameter Values

Parameter Description
start Required. The starting index of the segment to be extracted; the first character is at position 0. If negative, it is taken from the tail.
end Optional. The index immediately after the end of the segment to be extracted. If this parameter is not specified, the extracted substring includes the characters from start to the end of the original string. If this parameter is negative, it specifies a position counted from the tail of the string. slice(-2) extracts the second-to-last element to the last element (including the last element) from the original array.

Return Value

Type Description
String The extracted string.

Technical Details

JavaScript Version: 1.0


More Examples

Example

Extract the whole string:

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

The output result of the above example:

Hello world!

Try it Yourself »

Example

Extract the string segment from position 3 of the string:

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

The output result of the above example:

lo world!

Try it Yourself »

Example

Extract the string segment from position 3 to position 8 of the string:

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

The output result of the above example:

lo wo

Try it Yourself »

Example

Extract only the first character:

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

The output result of the above example:

H

Try it Yourself »

Example

Extract the last character and the last two characters:

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

The output result of the above example:

!
d!

Try it Yourself »


String 对象参考手册JavaScript String Object

Other Extensions