slice

 

Summary

Extracts a section of a string and returns a new string.

Method of String
Implemented in JavaScript 1.0
ECMAScript Edition ECMAScript 3rd Edition

Syntax

string.slice(beginslice[, endSlice])

Parameters

beginSlice 
The zero-based index at which to begin extraction.
endSlice 
The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string.

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. string.slice(1,4) extracts the second character through the fourth character (characters indexed 1, 2, and 3).

As a negative index, endSlice indicates an offset from the end of the string. string.slice(2,-1) extracts the third character through the second to last character in the string.

Examples

Example: Using slice to create a new string

The following example uses slice to create a new string.

// assumes a print function is defined
var str1 = "The morning is upon us.";
var str2 = str1.slice(4, -2);
print(str2);

This writes:

morning is upon u

 

Tags (1)

Attachments (0)

 

Attach file