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.

Note

Strings in JavaScript are immutable, and the slice() method returns a new string without modifying the original:

const str = 'Coding Beauty';

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

// Original not modified
console.log(str); // Coding Beauty

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.

Note

substring() returns a new string without modifying the original:

const str = 'Coding Beauty';

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

// Original not modified
console.log(str); // Coding Beauty

Tip

The slice() and substring() work similarly for our use case, but this isn’t always so. Here’s one difference between them: substring() swaps its arguments if the first is greater than the second, but slice() returns an empty string ('').

const str = 'Coding Beauty';

const subStr1 = str.substring(2, 0);
const subStr2 = str.slice(2, 0);

// Equivalent to str.substring(0, 2)
console.log(subStr1); // Co

console.log(subStr2); // '' (empty string)


Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *