Extracting the beginning of a string is a very common task, essential for creating summaries, truncating long text for display, or getting a prefix from a filename. The modern and most idiomatic way to achieve this in JavaScript is with the String.prototype.slice() method.
This guide will teach you how to use slice() to get the first N characters of a string, explain how it differs from the similar substring() method, and show you why slice() is the recommended best practice.
The Core Method (Recommended): String.prototype.slice()
The slice() method is the most direct and powerful tool for this job. It extracts a section of a string and returns it as a new string, without modifying the original.
To get the first N characters, you call slice() with a starting index of 0 and an ending index of N. The slice will include the character at the start index up to, but not including, the character at the end index.
Syntax: myString.slice(0, N)
For example, you have a long string and need to get the first 10 characters.
// Problem: How to get the first 10 characters?
const longText = 'This is a very long sentence.';Solution:
const longText = 'This is a very long sentence.';
const N = 10;
const firstTenChars = longText.slice(0, N);
console.log(firstTenChars); // Output: "This is a "An Alternative Method: String.prototype.substring()
The substring() method is very similar to slice() and can be used in the same way for this specific task.
Solution:
const longText = 'This is a very long sentence.';
const N = 10;
const firstTenChars = longText.substring(0, N);
console.log(firstTenChars); // Output: "This is a "Why slice() is the Best Practice
Although slice() and substring() seem interchangeable for this simple task, they behave differently in other scenarios, and slice() is generally more intuitive and powerful.
- Negative Indexes:
slice()accepts negative indexes, which count from the end of the string.substring()treats negative indexes as0.'hello'.slice(-2); // Returns 'lo' 'hello'.substring(-2); // Returns 'hello' - Swapped Indexes: If the start index is greater than the end index,
slice()returns an empty string, which is logical.substring()will swap the two arguments.'hello'.slice(3, 0); // Returns '' 'hello'.substring(3, 0); // Returns 'hel' (same as substring(0, 3))
Because its behavior is more predictable and consistent, slice() is the recommended best practice for all substring operations.
Practical Example: Truncating a Text Preview
A perfect use case for slice() is to create a short preview of a longer piece of text, adding an ellipsis (...) at the end.
function truncate(str, maxLength) {
if (str.length <= maxLength) {
return str;
}
// Get the first `maxLength` characters and add an ellipsis
return str.slice(0, maxLength) + '...';
}
// Example Usage:
const longPost = 'This is a long blog post about JavaScript performance and best practices.';
const preview = truncate(longPost, 30);
console.log(preview);
// Output: "This is a long blog post abou..."Conclusion
For getting the first N characters of a string, the String.prototype.slice() method is the definitive best practice.
- The syntax is clean and direct:
myString.slice(0, N). - It is the most predictable and powerful substring method in JavaScript, especially when compared to
substring(). - It safely handles cases where
Nis larger than the string's length.
By using slice(), you can write clean, readable, and robust code for any string truncation or extraction task.