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

11 Amazing New Features in ES13

11 Amazing New Features in ES13
Get up to speed with all the latest features added in ECMAScript 13 to modernize your JavaScript with shorter and more expressive code.

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.

See also