How to Get the First N Characters of a String in JavaScript
Learn how to easily get the first characters of a string up to a certain number using JavaScript.
1. slice() Method
To get the first N
characters of a string in JavaScript, call the slice()
method on the string, passing 0
as the first argument and N
as the second. For example, str.slice(0, 2)
returns a new string containing the first 2 characters of str
.
const str = 'Coding Beauty';const first2 = str.slice(0, 2);
console.log(first2); // Coconst first6 = str.slice(0, 6);
console.log(first6); // Codingconst first8 = str.slice(0, 8);
console.log(first8); // Coding B
The String
slice()
method extracts the part of a string between the start and end indexes, which are specified by the first and second arguments respectively. The substring between the indexes 0
and N
is a substring containing only the first N
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. substring() Method
To get the first N
characters of a string, we can also call the substring()
method on the string, passing 0
and N
as the first and second arguments respectively. For example, str.substring(0, 3)
returns a new string containing the first 3 characters of str
.
const str = 'Coding Beauty';const first3 = str.substring(0, 3);
console.log(first3); // Codconst first5 = str.substring(0, 5);
console.log(first5); // Codinconst first11 = str.substring(0, 11);
console.log(first11); // Coding Beau
Like slice()
, substring()
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 first3 = str.substring(0, 3);
console.log(first3); // Cod// Original not modified
console.log(str); // Coding Beauty
Tip
The slice()
and substring()
methods work similarly for our scenario, but this isn't always the case. 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); // Coconsole.log(substr2); // '' (empty string)
Updated at: codingbeautydev.com
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.
Sign up and receive a free copy immediately.