JavaScript to keep only first N characters in a string
In this article, we are given a string and the task is to keep only the 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 the start index to the end index. Indexing starts from zero (0).
Syntax:
string.substring(Startindex, Endindex)
Example: This example uses the above-explained approach.
javascript
<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 that is used to return a part or slice of the given input string.
Syntax:
string.slice(startingindex, endingindex)
Example: This example shows the above-explained approach.
javascript
<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"
Please Login to comment...