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.
See also
- How to Get the Last Two Characters of a String in JavaScript
- How to Get the First N Characters of a String in JavaScript
- How to Get the Substring Between Two Characters in JavaScript
- How to Get the Last N Characters of a String in JavaScript
- How to get the difference between two arrays in JavaScript
- How to get the difference between two sets in JavaScript