JavaScript - slice() method

revision:


Category : array

The slice() method returns a shallow copy of a portion of an array into a new array object selected from "start" to "end" ("end" not included) where "start" and "end" represent the "index" of items in that array. The original array will not be modified.

Syntax :

        slice()
        slice(start)
        slice(start, end)        
    

Parameters:

start : optional. Zero-based index at which to start extraction, converted to an integer.

Negative index counts back from the end of the array — if "start < 0", "start + array.length" is used.
If "start < -array.length" or "start is omitted", 0 is used.
If "start >= array.length", nothing is extracted.

end : optional. Zero-based index at which to end extraction, converted to an integer. slice() extracts up to but not including "end".

Negative index counts back from the end of the array — if "end < 0", "end + array.length" is used.
If "end < -array.length", 0 is used.
If "end >= array.length" or "end is omitted", "array.length" is used, causing all elements until the "end" to be extracted.
If "end" is positioned before or at "start" after normalization, nothing is extracted.

Examples:

            const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
            console.log(animals.slice(2));
            // Expected output: Array ["camel", "duck", "elephant"]
            console.log(animals.slice(2, 4));
            // Expected output: Array ["camel", "duck"]
            console.log(animals.slice(1, 5));
            // Expected output: Array ["bison", "camel", "duck", "elephant"]
            console.log(animals.slice(-2));
            // Expected output: Array ["duck", "elephant"]
            console.log(animals.slice(2, -1));
            // Expected output: Array ["camel", "duck"]
             console.log(animals.slice());
            // Expected output: Array ["ant", "bison", "camel", "duck", "elephant"] 
        

Category : string

The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. It 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.

Syntax :

        string.slice(start, end)        
    

Parameters:

start : required. The start position. (First character is 0).

end : optional. The end position (up to, but not including). Default is string length.

Examples:

            <p>slice() extracts a part of a string and returns the extracted part:</p>
            <p id="demo"></p>
            <script>
                let text = "Hello world!";
                let result = text.slice(0, 5);
                document.getElementById("demo").innerHTML = result;
            </script>

        

Practical examples

example: return a portion of an existing array.

code:
                    <div>
                        <p id="slice-1"></p>
                        <p id="slice-2"></p>
                    </div>
                    <script>
                        const fruits = ["Banana", " Orange", " Lemon", " Apple", " Mango"];
                        document.getElementById("slice-1").innerText = "fruits : " + fruits;
                        const citrus = fruits.slice(1, 3);
                        document.getElementById("slice-2").innerText = "citrus : " + citrus;
                        // fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
                        // citrus contains ['Orange','Lemon']
            
                    </script>
                

example: using slice() method.

code:
                    <div>
                        <p id="slice-3"></p>
                        <p id="slice-4"></p>
                        <p id="slice-5"></p>
                        <p id="slice-6"></p>
                        <p id="slice-7"></p>
                        <p id="slice-8"></p>
                        <p id="slice-9"></p>
                    </div>
                    <script>
                            // Using slice, create newCar from myCar.
                            const myHonda = {
                            color: "red",
                            wheels: 4,
                            engine: { cylinders: 4, size: 2.2 },
                            };
                            const myCar = [myHonda, 2, "cherry condition", "purchased 1997"];
                            const newCar = myCar.slice(0, 2);
                            document.getElementById("slice-3").innerHTML = "my car: " + JSON.stringify(myHonda);
                            console.log("myCar =", myCar);
                            console.log("newCar =", newCar);
                            console.log("myCar[0].color =", myCar[0].color);
                            console.log("newCar[0].color =", newCar[0].color);
                            document.getElementById("slice-4").innerHTML = "my car: " + JSON.stringify(myCar);
                            document.getElementById("slice-5").innerHTML = "new car: " + JSON.stringify(newCar);
                            document.getElementById("slice-6").innerHTML = "new car color: " + JSON.stringify(newCar[0].color);
                            // Change the color of myHonda.
                            myHonda.color = "purple";
                            console.log("The new color of my Honda is", myHonda.color);
                            document.getElementById("slice-7").innerHTML = "new Honda color: " + myHonda.color;
                            console.log("myCar[0].color =", myCar[0].color);
                            console.log("newCar[0].color =", newCar[0].color);
                            document.getElementById("slice-8").innerHTML = "my car color: " + myCar[0].color;
                            document.getElementById("slice-9").innerHTML = "new car color: " + newCar[0].color;
            
                    </script>
                

example: select elements using negative values

code:
                    <div>
                        <p id="slice-10"></p>
                        <p id="slice-11"></p>
                    </div>
                    <script>
                        const fruits1 = [" Banana", " Orange", " Lemon", " Apple", " Mango"];
                        document.getElementById("slice-10").innerHTML = "original array : " + fruits1;            
                        const myBest = fruits1.slice(-3, -1);
                        document.getElementById("slice-11").innerHTML = "sliced array : " + myBest;
                        
                    </script>
                

example: slice some positions

code:
                    <div>
                        <p id="slice-12"></p>
                        <p id="slice-13"></p>
                        <p id="slice-14"></p>
                        <p id="slice-15"></p>
                        <p id="slice-16"></p>
                        <p id="slice-17"></p>
                        <p id="slice-18"></p>
                        <p id="slice-19"></p>
            
                    </div>
                    <script>
                        let text = "Hello world!";
                        document.getElementById("slice-12").innerHTML = "string : " + text;
                        let result = text.slice(0, 5);
                        document.getElementById("slice-13").innerHTML = "sliced : " + result;
                        let result1 = text.slice(3);
                        document.getElementById("slice-14").innerHTML = "sliced : " + result1;
                        let result2 = text.slice(3, 8);
                        document.getElementById("slice-15").innerHTML = "sliced : " + result2;
                        let result3 = text.slice(0, 1);
                        document.getElementById("slice-16").innerHTML = "sliced : " + result3;
                        let result4 = text.slice(-1);
                        document.getElementById("slice-17").innerHTML = "sliced : " + result4;
                        let result5 = text.slice();
                        document.getElementById("slice-17").innerHTML = "sliced : " + result5;
                    </script>