JavaScript String Slice() Method - W3Schools

JavaScript String slice() ❮ Previous JavaScript String Reference Next

Examples

Slice the first 5 positions:

let text = "Hello world!"; let result = text.slice(0, 5); Try it Yourself »

From position 3 to the end:

let result = text.slice(3); Try it Yourself »

More examples below.

Description

The slice() method extracts a part of a string.

The slice() method returns the extracted part in a new string.

The slice() method does not change the original string.

The start and end parameters specifies the part of the string to extract.

The first position is 0, the second is 1, ...

A negative number selects from the end of the string.

See Also

The split() Method

The substr() Method

The substring() Method

Syntax

string.slice(start, end)

Parameters

Parameter Description
start Required.The start position.(First character is 0).
end Optional.The end position (up to, but not including). Default is string length.

Return Value

Type Description
A stringThe extracted part of the string.

More Examples

From position 3 to 8:

let result = text.slice(3, 8); Try it Yourself »

Only the first character:

let result = text.slice(0, 1); Try it Yourself »

Only the last character:

let result = text.slice(-1); Try it Yourself »

The whole string:

let result = text.slice(0); Try it Yourself »

Related Pages

JavaScript Strings

JavaScript String Methods

JavaScript String Search

Browser Support

slice() is an ECMAScript1 (JavaScript 1997) feature.

It is supported in all browsers:

Chrome Edge Firefox Safari Opera
Previous JavaScript String Reference Next +1 Sign in to track progress

Từ khóa » Cắt Xâu Javascript