1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
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.
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 from start
to end-1
(So exclusive of end character index).
Remember, the original string remains unchanged, so be sure to assign the result to a variable.
Now, let’s explore String.substring()
:
const originalString = "JavaScriptRocks";
const firstFourCharacters = originalString.substring(0, 4);
console.log(firstFourCharacters); // Output: "Java"
Explanation:
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.
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.
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.
end
index is greater than the start
index to avoid unexpected results.end
is omitted in slice(), it defaults to the length of the string.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.
Problem (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:
Solution (JavaScript)
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 🚀!
Feel free to reach out!