Skip to content
Related Articles

Related Articles

JavaScript string.slice() Method

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 06 Oct, 2021

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

  • Example: 
     

javascript




<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>


  • 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: 
 

javascript




<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>


Output: 
 

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

Code #2: 
 

javascript




<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>


Output: 
 

Geeks for Geek

 

Supported Browser:

  • Chrome 1 and above
  • Edge 12 and above
  • Firefox 1 and above
  • Internet Explorer 4 and above
  • Opera 4 and above
  • safari 1 and above


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!