Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Array slice() Method

JavaScript Array slice() Method

Array Object Reference JavaScript Array object

Example

Read elements from an array:

var

fruits

=

[

"

Banana

"

,

"

Orange

"

,

"

Lemon

"

,

"

Apple

"

,

"

Mango

"

]

;

var

citrus

=

fruits

.

slice

(

1

,

3

)

;

citrus Output result:

Orange,Lemon

Try it »


Definition and Usage

The slice() method returns selected elements from an existing array.

The slice() method can extract a portion of a string and return the extracted portion as a new string.

Note: The slice() method does not change the original array.


Browser support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support slice().


Syntax

array

.slice(

start

,

end

)

Parameter Values

Parameters Description
start Optional. Specifies where to start the selection. If this parameter is negative, it indicates starting extraction from the nth element counting from the end of the original array; slice(-2) means extracting the second-to-last element to the last element of the original array (including the last element).
end Optional. Specifies where to end the selection. This parameter is the array index at the end of the array fragment. If this parameter is not specified, the sliced array contains all elements from start to the end of the array. If this parameter is negative, it indicates ending extraction at the nth element counting from the end of the original array. slice(-2,-1) means extracting the second-to-last element to the last element of the original array (excluding the last element, that is, only the second-to-last element).

Return Value

Type Description
Array Returns a new array containing the elements of arrayObject from start (including that element) to end (excluding that element).

Technical Details

JavaScript version: 1.2

More examples

Example

Read elements from an array using negative values

var

fruits

=

[

"

Banana

"

,

"

Orange

"

,

"

Lemon

"

,

"

Apple

"

,

"

Mango

"

]

;

var

myBest

=

fruits

.

slice

(

3

,-

1

)

;

//

Extract the third-to-last (inclusive) to the first-to-last (exclusive) two elements

var

myBest

=

fruits

.

slice

(

3

)

;

//

Extract the last three elements

myBest Output result:

Lemon,Apple

Try it »

Example

Extract a string

var

str

=

"

www.runoob.com!

"

;

document

.

write

(

str

.

slice

(

4

)

"


"

)

;

//

Extract from the 5th character to the end

document

.

write

(

str

.

slice

(

4

,

10

)

)

;

//

Extract from the 5th character to the 10th character

Try it »


Array Object Reference JavaScript Array object