Swap String Case with JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28638{{"`Swap String Case with JavaScript`"}} javascript/data_types -.-> lab-28638{{"`Swap String Case with JavaScript`"}} javascript/arith_ops -.-> lab-28638{{"`Swap String Case with JavaScript`"}} javascript/comp_ops -.-> lab-28638{{"`Swap String Case with JavaScript`"}} javascript/higher_funcs -.-> lab-28638{{"`Swap String Case with JavaScript`"}} javascript/spread_rest -.-> lab-28638{{"`Swap String Case with JavaScript`"}} end

How to Swapcase a String in JavaScript

To swap the case of a string in JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the spread operator (...) to convert the input string str into an array of characters.
  3. Use String.prototype.toLowerCase() and String.prototype.toUpperCase() to convert lowercase characters to uppercase and vice versa.
  4. Use Array.prototype.map() to apply the transformation to each character, and Array.prototype.join() to combine the characters back into a string.
  5. 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.

Other JavaScript Tutorials you may like