mozilla
Your Search Results

    String.prototype.slice()

    Summary

    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.

    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

    Example: 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
    

    Example: 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'
    

    Specifications

    Specification Status Comment
    ECMAScript 3rd Edition. Standard Initial definition. Implemented in JavaScript 1.2.
    ECMAScript 5.1 (ECMA-262)
    The definition of 'String.prototype.slice' in that specification.
    Standard  
    ECMAScript 6 (ECMA-262)
    The definition of 'String.prototype.slice' in that specification.
    Draft  

    Browser compatibility

    Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
    Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
    Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
    Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

    See also

    Document Tags and Contributors

    Last updated by: Mingun,
    Hide Sidebar