How to use String’s substr() Method In Javascript
The substr() method is used to extract parts of a string, beginning at the specified start position, and returns the specified number of characters.
Syntax:
string.substr(startIndex, length)
Example:
// JavaScript to keep only first
// 'n' characters of String
// Original string
let str = "Hello World";
// Keep first 5 characters
let n = 5;
console.log("Original String = " + str);
console.log("n = " + n);
// Using substr() method
str = str.substr(0, n);
console.log("Keep first " + n +
" characters of original String = " + str);
Output
Original String = Hello World n = 5 Keep first 5 characters of original String = Hello
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: