How to use Array.prototype.join() with Array.from() In Javascript
The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object. By converting the string into an array of characters, we can easily manipulate and then join the desired portion back into a string.
Example: This example demonstrates using Array.from() to convert the string to an array of characters, then slicing and joining them to keep only the first n characters.
// JavaScript to keep only first 'n' characters of String
// Original string
let str = "OpenAI GPT-4";
// Keep first 8 characters
let n = 8;
console.log("Original String = " + str);
console.log("n = " + n);
// Using Array.from() and join() method
str = Array.from(str).slice(0, n).join('');
console.log("Keep first " + n + " characters of original String = " + str);
Output
Original String = OpenAI GPT-4 n = 8 Keep first 8 characters of original String = OpenAI G
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: