JavaScript to keep only first N characters in a string

Given a string and the task is to keep only first n characters of the string. There are various methods to solve this problem in JavaScript, some of them are discussed below:

Method 1: Using substring() Method: The string.substring() method is an inbuilt function in JavaScript which is used to return the part of the given string from start index to end index. Indexing starts from zero (0).

Syntax:



string.substring(Startindex, Endindex)

Below program demonstrates the above approach.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    // JavaScript to keep only first
    // 'n' characters of String
      
    // Original string
    var str = "GeeksforGeeks";
      
    // Keep first 5 letters
    var n = 5;
      
    document.write("Original String = \""
                    + str + "\"<br>");
    document.write("n = " + n + "<br>");
      
    // Using substring() method
    str = str.substring(0, n);
      
    document.write("Keep first " + n + 
        " characters of original String = \""
        + str + "\"<br>");
</script>                                     

chevron_right


Output:

Original String = "GeeksforGeeks"
n = 5
Keep first 5 characters of original String = "Geeks"

Method 2: Using slice() Method: The string.slice() is an inbuilt function in javascript which is used to return a part or slice of the given input string.

Syntax:

string.slice(startingindex, endingindex)

Below program demonstrates the above approach.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    // JavaScript script to keep only
    // first 'n' characters of String
      
    // Original string
    var str = "Data Structure";
      
    // Keep first 11 letters
    var n = 11;
      
    document.write("Original String = \""
                    + str + "\"<br>");
    document.write("n = " + n + "<br>");
      
    // Using slice() method
    str = str.slice(0, n);
      
    document.write("Keep first " + n + 
        " characters of original String = \""
        + str + "\"<br>");
</script>                    

chevron_right


Output:

Original String = "Data Structure"
n = 11
Keep first 11 characters of original String = "Data Struct"


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.