How to use slice in JavaScript

This article describe about slice() Method in JavaScript.
  • 1946

slice() Method in JavaScript

This method is used to returns the selected elements in an array.

This method select the elements starting at the given start argument, and ends at also, but it doesn't include the given end argument.

Example

<!DOCTYPE html>

<html>

<body>

<p id="demo">When you click on the button extract the second and the third elements from the array.</p>

<button onclick="myFunction()">Click me</button>

<script type="text/javascript">

    function myFunction() {

        var vegetable = ["Brinjal", "Onion", "potato", "Green", "tomato"];

        var extract = vegetable.slice(1, 3);

        var x = document.getElementById("demo");

        x.innerHTML = extract;

    }

</script>

</body>

</html>

 

Output

 

pic17.jpg

 

Note: After click on the button second and third element extract from the array.

 

pic18.jpg

 

Syntax

 

array.slice(start, end)

 

Parameter values

 

Parameter Description
start Required. Integer value that specified to start.
end Optional. Integer value that specified to end

Technical details

JavaScript version: 1.2

You may also want to read these related articles Click here

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.