Skip to content
Related Articles

Related Articles

JavaScript to keep only first N characters in a string
  • Last Updated : 31 May, 2019

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:






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

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:




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

Output:

Original String = "Data Structure"
n = 11
Keep first 11 characters of original String = "Data Struct"
My Personal Notes arrow_drop_up
Recommended Articles
Page :