Borislav Hadzhiev
Sun Oct 24 2021·2 min read
Photo by Luke Dahlgren
To get the first three characters of a string, call the substring()
method
and pass it 0
and 3
as parameters. The substring
method will return a new
string containing the first three characters of the original string.
const str = 'Walk the dog'; const first3 = str.substring(0, 3); console.log(first3); // 👉️ Wal
The two parameters we passed to the String.substring method are:
0
and the last is str.length - 1
.To get the index of the first three characters, we specified a start index of
0
and an end index of 3
, this extracts characters at positions: 0
, 1
and
2
.
An alternative approach is to use the String.slice method.
To get the first three characters of a string, call the slice()
method,
passing it 0
as the first parameter and 3
as the second. The method will
return a new string containing the first three characters of the original
string.
const str = 'Walk the dog'; const first3 = str.slice(0, 3); console.log(first3); // 👉️ Wal
We passed the same parameters to the slice
method as we did with the
substring
method, however the methods are not identical.
For our purposes, the slice
and substring
methods do the same, however there
are some differences between the two for other use cases. If you want to read
more on that, check out the section in the
MDN docs.
String.slice
method because it's shorter, easier to read and more intuitive than String.substring
for other use cases mentioned in the MDN docs.