How to Get the First N Characters of a String in JavaScript

Last updated on June 25, 2022
How to Get the First N Characters of a String in JavaScript

1. String slice() Method

To get the first N characters of a string in JavaScript, call the slice() method on the string, passing 0 as the first argument and N as the second. For example, str.slice(0, 2) returns a new string containing the first 2 characters of str.

const str = 'Coding Beauty';

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

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

const first8 = str.slice(0, 8);
console.log(first8); // Coding B

The String slice() method extracts the part of a string between the start and end indexes, which are specified by the first and second arguments respectively. The substring between the indexes 0 and N is a substring containing only the first N string characters.

2. String substring() Method

To get the first N characters of a string, we can also call the substring() method on the string, passing 0 and N as the first and second arguments respectively. For example, str.substring(0, 3) returns a new string containing the first 3 characters of str.

const str = 'Coding Beauty';

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

const first5 = str.substring(0, 5);
console.log(first5); // Codin

const first11 = str.substring(0, 11);
console.log(first11); // Coding Beau

Like slice(), substring() returns the part of a string between the start and end indexes, which are specified by the first and second arguments respectively.

Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also