You can use the slice() method to get the first N characters of a string in JavaScript, passing 0 as the first parameter and N as the second parameter.

The slice() method takes the start and end indexes as parameters and returns a new string containing a slice of the original string.

const str = 'JavaScript'

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

const first6 = str.slice(0, 6)
console.log(first6) // JavaSc

const first9 = str.slice(0, 9)
console.log(first9) // JavaScrip

The slice() method extracts a part of a string between the start and end indexes, specified as first and second parameters. It returns the extracted part as a new string and does not change the original string.

If you provide an end index greater than the string's length, the slice() method does not throw an error. Instead, it returns a copy of the original string:

const str = 'JavaScript'

const first20 = str.slice(0, 20)
console.log(first20) // JavaScript

You could also use the substring() method to get the first N characters of a string in JavaScript:

const str = 'JavaScript'

const first4 = str.substring(0, 4)
console.log(first4) // Java

The substring() method works similarly to slice() and returns a new string containing part of the original string specified using start and end indexes.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.