JavaScript to keep only first N characters in a string
Last Updated :
20 Jul, 2023
In this article, we have given a string and the task is to keep only the first n characters of the string using JavaScript. There are various methods to solve this problem, some of which are discussed below:
Methods to keep only First N characters in a String:
The string.substring() method 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
let str = "GeeksforGeeks" ;
let n = 5;
console.log( "Original String = " + str);
console.log( "n = " + n);
str = str.substring(0, n);
console.log( "Keep first " + n +
" characters of original String = " + str);
|
Output
Original String = GeeksforGeeks
n = 5
Keep first 5 characters of original String = Geeks
The string.slice() method is used to return a part or slice of the given input string.
Syntax:
string.slice(startingindex, endingindex)
Example: This example uses slice() method to get part of a string.
javascript
let str = "Data Structure" ;
let n = 11;
console.log( "Original String = " + str);
console.log( "n = " + n);
str = str.slice(0, n);
console.log( "Keep first " + n +
" characters of original String = " + str);
|
Output
Original String = Data Structure
n = 11
Keep first 11 characters of original String = Data Struct
Looping in programming languages is a feature that facilitates the execution of a set of instructions repeatedly until some condition evaluates and becomes false. We come across for loop which provides a brief and systematic way of writing the loop structure.
Syntax:
for (statement 1 ; statement 2 ; statement 3){
code here...
}
Example: In this example, we will loop till the given index and store characters in the result string.
Javascript
let str = "GeeksforGeeks" ;
let n = 5;
let res = "" ;
console.log( "Original String = " + str);
console.log( "n = " + n);
for (let i = 0; i < n; i++) {
res += str[i];
}
console.log(
"Keep first " + n +
" characters of original String = "
+ res
);
|
Output
Original String = GeeksforGeeks
n = 5
Keep first 5 characters of original String = Geeks
Share your thoughts in the comments
Please Login to comment...