what is the use of slice() method in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

slice()

The slice() method extracts a part of a string and returns the extracted part in a new string.It doesn't modify the original string.

syntax

slice() takes two parameters one is starting index and the other is ending index. It's notation is given below. 

string.slice(string.slice(starting index, ending index))

Arguments

   a) starting index: It gives from which index string extraction should be started.

   b) ending index: It gives before which index string extraction should be ended.

Example-1

In the following example, slice() method slice the given string in to new string starting from index 18 to 26 (27-1) there by giving "Neuralink" as the output.

 Live Demo

<html>
<body>
<p id="slice"></p>
<script>
   var string = "Tesla, Solarcity, Neuralink, Spacex";
   var newstring = string.slice(18,27);
   document.getElementById("slice").innerHTML = string;
</script>
</body>
</html>

Output

Neuralink

Example-2 

When only starting index parameter is provided then slice() method slices out entire string from the starting index and displays the output.

 since only starting index(18) is provided,Following example shows entire array from starting index

 Live Demo

<html>
<body>
<p id="slice"></p>
<script>
   var string = "Tesla, Solarcity, Neuralink, Spacex";
   var newstring = string.slice(18);
   document.getElementById("slice").innerHTML = newstring;
</script>
</body>
</html>

Output

Neuralink, Spacex
raja
Published on 29-May-2019 14:18:02
Advertisements