How to use slice() Method In Javascript
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 script to keep only
// first 'n' characters of String
// Original string
let str = "Data Structure";
// Keep first 11 letters
let n = 11;
console.log("Original String = " + str);
console.log("n = " + n);
// Using slice() method
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
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: