How to use substring() Method In Javascript
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 to keep only first
// 'n' characters of String
// Original string
let str = "w3wiki";
// Keep first 5 letters
let n = 5;
console.log("Original String = " + str);
console.log("n = " + n);
// Using substring() method
str = str.substring(0, n);
console.log("Keep first " + n +
" characters of original String = " + str);
Output
Original String = w3wiki n = 5 Keep first 5 characters of original String = Geeks
JavaScript to keep only first N characters in a string
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: