Welcome, fellow coders! In this blog, we’ll see how to extract the first N characters from a string. Whether you’re a beginner or just looking for a quick refresher, we’ve got you covered.
Method 1: String.slice()
The String.slice()
method is your first tool in the kit. Here’s how you can use it:
const originalString = "JavaScriptRocks";
const firstFourCharacters = originalString.slice(0, 4);
console.log(firstFourCharacters); // Output: "Java"
Explanation:
- The
slice(start, end)
method extracts characters fromstart
toend-1
(So exclusive of end character index). - Remember, the original string remains unchanged, so be sure to assign the result to a variable.
Method 2: String.substring()
Now, let’s explore String.substring()
:
const originalString = "JavaScriptRocks";
const firstFourCharacters = originalString.substring(0, 4);
console.log(firstFourCharacters); // Output: "Java"
Explanation:
- Similar to slice(), substring(start, end) extracts characters from start to end-1.
- Despite their similarities, slice() is generally preferred for its more intuitive implementation.
Differences Between slice() and substring()
Key distinctions between slice()
and substring()
are in handling of negative indices and omitted parameters. When working with string manipulation, understanding these differences can save you from unexpected results.
Handling negative indices
Both methods are similar, but one key difference is how they handle negative indices. slice()
allows negative indices, whereas substring()
treats them as 0.
const originalString = "JavaScriptRocks";
// Using slice() with negative indices
const slicedResult = originalString.slice(-6, -1);
console.log(slicedResult); // Output: "Rock"
// Using substring() with negative indices
const substringResult = originalString.substring(2, -1);
console.log(substringResult); // Output: "vaScriptRock"
In this example, slice()
gracefully handles negative indices by counting from the end of the string. However, substring() treats negative indices as 0, resulting in a different output.
Handling Omitted Parameters
Another difference is in handling the parameters. slice() accepts end as optional, defaulting to the end of the string. However, substring() interprets missing parameters as 0 or the string length.
const originalString = "JavaScriptRocks";
// Using slice() with omitted end parameter
const slicedResult = originalString.slice(2);
console.log(slicedResult); // Output: "vaScriptRocks"
// Using substring() with omitted end parameter
const substringResult = originalString.substring(2);
console.log(substringResult); // Output: "vaScriptRocks"
Here, slice()
defaults to the end of the string when the end
parameter is omitted. Similarly, substring()
interprets the absence of the end
parameter as the length of the string.
⚠ Common Gotchas:
- Always ensure that the
end
index is greater than thestart
index to avoid unexpected results. - If
end
is omitted in slice(), it defaults to the length of the string.
🧪Practice Coding Problem: Get First Property
In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.
Write a function
truncateGreeting(greeting, length)
that takes a greeting string and a length and returns a truncated greeting. If the length is greater than the greeting’s length, return the original string.JavaScript/** * Truncate the greeting to the specified length. * @param {string} greeting - The original greeting string. * @param {number} length - The desired length of the truncated greeting. * @returns {string} - The truncated greeting. */ function truncateGreeting(greeting, length) { // > > > 👉 Write code here 👈 < < < } // Test the function const originalGreeting = "Hello, fellow coders!"; const truncated = truncateGreeting(originalGreeting, 7); console.log(truncated); // Output: "Hello, "
Please attempt before seeing the Answer:
function truncateGreeting(greeting, length) {
// Check if length is greater than or equal to the greeting's length
if (length >= greeting.length) {
return greeting; // Return the original greeting
} else {
// Use String.slice() to extract the first N characters
const truncatedGreeting = greeting.slice(0, length);
return truncatedGreeting;
}
}
Explanation:
- The function checks if the specified length is greater than or equal to the length of the original greeting. If true, it returns the original greeting.
- If the length is less than the greeting’s length, it uses
String.slice(0, length)
to extract the first N characters and returns the truncated greeting.
Now you can Slice-n-Dice all your Javascript strings with ease. Now go ahead, practice your newfound chops. Keep coding 🚀!