4 Example(s) of Javascript slice function


Description :

JavaScript slice function is used to extract array from start index parameter to end index parameter. See the code snippet:


Javascript slice function Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
 <script>
    var vegs = ["Tomato", "Patato", "Lemon", "Cheese", "Carrot"];
    var result= vegs.slice(1, 4);
    document.write(result);
      </script>
</body>
</html>

Output

Description :

Javascript slice function will extract data from string or an array. It require two parameters one is start point and second parameter is optional. if negative values are assigned then it will start from the end.


Javascript slice function Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
        
</head>
<body>
   <script>
         var str = "i love learnkode, the code learning platform.";
         var sliced = str.slice(3, -2);
         document.write( sliced );
      </script>

</body>
</html>

Output

Description :

Example of slice with negative values


Javascript slice function Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
        
</head>
<body>
   <script>
         var str = "Apples are round, and apples are juicy.";
         var sliced = str.slice(-3, -2);
         document.write( sliced );
      </script>
</body>
</html>

Output

Description :

Javascript Slice function with one parameter:


Javascript slice function Example - 4
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
        
</head>
<body>
   <script>
         var str = "Apples are round, and apples are juicy.";
         var sliced = str.slice(4);
                  document.write( sliced );
      </script>

</body>
</html>

Output