Introduction
In this lab, we will explore how to create a JavaScript function that swaps the case of a given string. This lab will cover the use of the spread operator, String.prototype.toLowerCase(), String.prototype.toUpperCase(), and Array.prototype.map(). By the end of this lab, you will have a deeper understanding of how to manipulate strings in JavaScript.
How to Swapcase a String in JavaScript
To swap the case of a string in JavaScript, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the spread operator (
...) to convert the input stringstrinto an array of characters. - Use
String.prototype.toLowerCase()andString.prototype.toUpperCase()to convert lowercase characters to uppercase and vice versa. - Use
Array.prototype.map()to apply the transformation to each character, andArray.prototype.join()to combine the characters back into a string. - Note that swapping the case of a string twice might not necessarily result in the original string.
Here's an example code snippet that demonstrates how to swap the case of a string in JavaScript:
const swapCase = (str) =>
[...str]
.map((c) => (c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase()))
.join("");
swapCase("Hello world!"); // Output: 'hELLO WORLD!'
Summary
Congratulations! You have completed the Swapcase String lab. You can practice more labs in LabEx to improve your skills.