offline version v3


65 of 264 menu

slice method

The slice method returns a substring from a string (the original string is not changed). The first parameter specifies the character number of the string from which the cutting starts, and the second parameter is the character number where the cutting will end (in this case, the character with this number will not be included in the cut part). The second parameter is optional. If it is not specified, the substring will be taken from the character specified in the first parameter to the end of the string. It can also take negative values. In this case, the character count at which the cut ends starts from the end of the string. The last character has number -1.

Syntax

string.slice(where to start, [where to stop]);

Example

Let a string be given. Let's cut out the characters from the first to the third:

let str = 'abcde'; let sub = str.slice(1, 3); console.log(sub);

The code execution result (character numbered 3 will not be included in the substring):

'bc'

Example

Let's now cut out the characters from 1st to the end of a string (for this, we will not set the second parameter of the method):

let str = 'abcde'; let sub = str.slice(1); console.log(sub);

The code execution result:

'bcde'

Example

Let's now cut the characters from position 1 to position -2:

let str = 'abcde'; let sub = str.slice(1, -2); console.log(sub);

The code execution result (character numbered -2 will not be included in the substring):

'bc'

See also

enru