The Wayback Machine - https://web.archive.org/web/20230512160259/https://www.geeksforgeeks.org/javascript-string-slice/
Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

JavaScript string.slice() Method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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

string.slice(startingIndex, endingIndex)

Parameters: This method uses two parameters. This method does not change the original string.

  • startingIndex: from which index, the extraction of the string should be started.
  • endingIndex: before which index, the extraction of the string should be included.

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

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

Example 1: 

javascript




<script>
    var A = 'Geeks for Geeks'; 
    b = A.slice(0,5); 
    c = A.slice(6,9); 
    d = A.slice(10); 
       
    console.log(b); 
    console.log(c); 
    console.log(d); 
</script>

Output: 

Geeks
for
Geeks

Some more examples are shown below:

Example 2:  

javascript




<script>
    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);
    console.log(b);
    console.log(c);
    console.log(d);
    console.log(e);      
</script>

Output: 

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

Example 3: 

javascript




<script>
    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); 
      
    console.log(b); 
    console.log(c); 
</script>

Output: 

Geeks for Geek

We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.
 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

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.


My Personal Notes arrow_drop_up
Last Updated : 28 Nov, 2022
Like Article
Save Article
Similar Reads
Related Tutorials