How to get the first N characters from a String in JavaScript

Javascript get first n characters of string example; In this tutorial we will show you how to get get the first N characters of a string in javascript

In Javascript we can use slice method on the string to pass in 0 as the first parameter and the number of characters to get as the second for getting the first n character from string.

Example:

const str = 'Coding Driver';

const first2 = str.slice(0, 2);
console.log(first2); // Co

const first3 = str.slice(0, 3);
console.log(first3); // Cod

The first parameter we pass to the String.slice method is the start index – the index at which we begin extraction of characters.

The second parameter is the end index – extract characters up to this index, but not including.