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

JavaScript String slice() Method

JavaScript String slice() Method

String Object Reference JavaScript String object

Example

Extract a fragment of a string:

var str="Hello world!";

var n=str.slice(1,5);

n Output result:

ello

Try it »


Definition and Usage

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

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

In the start parameter, the position of the first character in the string is 0, the second character position is 1, and so on. If it is negative, it indicates how many characters to extract from the end; slice(-2) means extracting the second-to-last element to the last element of the original array (including the last element).

If the end parameter is negative, -1 refers to the position of the last character of 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 value

Parameters Description
start Required. The starting index of the fragment to extract, with the first character position being 0. If negative, extraction starts from the end.
end Optional. The index immediately after the end of the fragment to be extracted. If this parameter is not specified, the substring to be extracted includes the string from start to the end of the original string. If this parameter is negative, it specifies a position counted from the end of the string. slice(-2) means extracting the second-to-last element to the last element of the original array (including the last element).

Return Value

Type Description
String The extracted string

Technical Details

JavaScript version: 1.0

More examples

Example

Extract all strings:

var str="Hello world!";

var n=str.slice(0);

The example above produces the following output:

Hello world!

Try it »

Example

Extract a string fragment starting from position 3 of the string:

var str="Hello world!";

var n=str.slice(3);

The example above produces the following output:

lo world!

Try it »

Example

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

var str="Hello world!";

var n=str.slice(3,8);

The example above produces the following output:

lo wo

Try it »

Example

Extract only the first character:

var str="Hello world!";

var n=str.slice(0,1);

The example above produces the following output:

H

Try it »

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 example above produces the following output:

!

d!

Try it »


String Object Reference JavaScript String object