How to get the first N characters of a string in JavaScript

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.