DroidScript

JavaScript Reference

str.slice()

The slice() method extracts a section of a string and returns a new string.

Syntax

str.slice(beginSlice[, endSlice])

Parameters

beginSlice
The zero-based index at which to begin extraction. If negative, it is treated as sourceLength + beginSlice where sourceLength is the length of the string (for example, if beginSlice is -3 it is treated as sourceLength - 3).
endSlice
Optional. The zero-based index at which to end extraction. If omitted, slice() extracts to the end of the string. If negative, it is treated as sourceLength + endSlice where sourceLength is the length of the string (for example, if endSlice is -3 it is treated as sourceLength - 3).

Description

slice() extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string.

slice() extracts up to but not including endSlice. str.slice(1, 4) extracts the second character through the fourth character (characters indexed 1, 2, and 3).

As an example, str.slice(2, -1) extracts the third character through the second to last character in the string.

Examples

Using slice() to create a new string

The following example uses slice() to create a new string.

var str1 = 'The morning is upon us.';
var str2 = str1.slice(4, -2);

console.log(str2); // OUTPUT: morning is upon u

Using slice() with negative indexes

The following example uses slice() with negative indexes.

var str = 'The morning is upon us.';
str.slice(-3);     // returns 'us.'
str.slice(-3, -1); // returns 'us'
str.slice(0, -1);  // returns 'The morning is upon us'

 Created by Mozilla Contributors and licensed under CC-BY-SA 2.5