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

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

1. String slice() Method

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

const str = 'Coding Beauty';

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

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

2. String substring() Method

Alternatively, to get the first two characters of a string, we can call the substring() method on the string, passing 0 and 2 as the first and second arguments respectively. For example, str.substring(0, 2) returns a new string containing the first two characters of str.

const str = 'Coding Beauty';

const firstTwoChars = str.substring(0, 2);
console.log(firstTwoChars); // Co

Like slice(), the substring() method 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