JavaScript string.slice() Method

Below is the example of the string.slice() Method.

  • Example:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script>                     
        var A = 'Geeks for Geeks'
      
        b = A.slice(0,5); 
        c = A.slice(6,9); 
        d = A.slice(10); 
       
        document.write(b +"<br>"); 
        document.write(c +"<br>"); 
        document.write(d +"<br>"); 
          
    </script> 

    chevron_right

    
    

  • Output:
    Geeks
    for
    Geeks

The string.slice() is an inbuilt method in javascript which is used to return a part or slice of the given input string.

Syntax:

string.slice(startingindex, endingindex)

Parameter: This method uses two-parameter startingindex( from which index, the string should be started) and endingindex (before which index, the string should be included).

Return Values: It returns a part or a slice of the given input string.



JavaScript code to show the working of the string.slice() method:
Code #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>                    
   
   // Taking a string as input.
   var A = 'Ram is going to school';
     
   // Calling of slice() function.
   b = A.slice(0, 5);
  
   // Here starting index is 1 given
   // and ending index is not given to it so
   // it takes to the end of the string  
   c = A.slice(1);
     
   // Here endingindex is -1 i.e, second last character
   // of the given string.
   d = A.slice(3, -1);
   e = A.slice(6);
   document.write(b +"<br>");
   document.write(c +"<br>");
   document.write(d +"<br>");
   document.write(e);    
     
</script>

chevron_right


Output:

Ram i
am is going to school
is going to schoo
going to school

Code #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>    
    // Taking a string as input.
    var A = 'Geeks for Geeks'
  
    // Calling of slice() function.
    // Here starting index is -1 given
    b = A.slice(-1,5); 
    // Here endingindex is -1 i.e
    c = A.slice(0,-1); 
  
    document.write(b +"<br>"); 
    document.write(c +"<br>"); 
      
</script> 

chevron_right


Output:


Geeks for Geek

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.