Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript - Characterrs to Opposite Case in a String
Next article icon

JavaScript - Characterrs to Opposite Case in a String

Last Updated : 17 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Here are the various approaches to convert each character of a string to its opposite case (uppercase to lowercase and vice versa).

Using for Loop and if-else Condition - Most Common

In this approach, we iterate through each character of the string. Using an if-else statement, it checks if each character is uppercase or lowercase and converts it accordingly.

JavaScript
const s1 = "Hello World";  let s2 = ""; for (let i = 0; i < s1.length; i++) {     const char = s1[i];     s2 += char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase(); } console.log(s2); 

Output
hELLO wORLD 

Using ASCII Values

Using ASCII values, you can determine whether a character is uppercase or lowercase, then convert it by adjusting its ASCII code. This method is useful for complex strings.

JavaScript
const s1 = "Hello World";  let s2 = ""; for (let i = 0; i < s1.length; i++) {     const charCode = s1.charCodeAt(i);     if (charCode >= 65 && charCode <= 90) {         s2 += String.fromCharCode(charCode + 32);     } else if (charCode >= 97 && charCode <= 122) {         s2 += String.fromCharCode(charCode - 32);     } else {         s2 += s1[i];     } } console.log(s2);  

Output
hELLO wORLD 

Using replace() Method with Regular Expression

The replace() method, along with a regular expression, can convert uppercase letters to lowercase and vice versa in a single line.

JavaScript
const s1 = "Hello World";  // Use replace with regex to swap case const s2 = s1.replace(/[a-zA-Z]/g, char =>     char === char.toUpperCase() ?          char.toLowerCase() : char.toUpperCase() ); console.log(s2); 

Output
hELLO wORLD 

Using split() and map() Method

The split() method splits the string into an array of characters, uses map() to change the case of each character, and then joins the array back into a string.

JavaScript
const s1 = "Hello World";  const s2 = s1     .split("")     .map(char => (char === char.toUpperCase() ?          char.toLowerCase() : char.toUpperCase()))     .join(""); console.log(s2); 

Output
hELLO wORLD 

Using the reduce Method

The reduce() method goes through each character in the string, turning it into an array. For each character, it adds the opposite case (uppercase becomes lowercase and vice versa) to the result. Finally, it joins everything back into a single string.

JavaScript
function swapCase(str) {     return str.split('').reduce((acc, char) => {         return acc + (char === char.toUpperCase() ?             char.toLowerCase() : char.toUpperCase());     }, ''); }  console.log(swapCase("Hello World!"));  

Output
hELLO wORLD! 

Using Array.from() Method

Array.from() converts the string into an array, allowing you to change each character’s case and join them back together.

JavaScript
const s1 = "Hello World";  const s2 = Array.from(s1, char =>     char === char.toUpperCase() ?          char.toLowerCase() : char.toUpperCase() ).join(""); console.log(s2); 

Output
hELLO wORLD 

Using for…of Loop and Ternary Operator

We can combine for...of loop with a ternary operator to check and convert each character’s case.

JavaScript
const s1 = "Hello World";  let s2 = ""; for (const char of s1) {     s2 += char === char.toUpperCase() ?         char.toLowerCase() : char.toUpperCase(); } console.log(s2);  

Output
hELLO wORLD 

Next Article
JavaScript - Characterrs to Opposite Case in a String

G

gauravggeeksforgeeks
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • javascript-string
  • Geeks Premier League 2023

Similar Reads

    Convert a String to a List of Characters in Java
    In Java, to convert a string into a list of characters, we can use several methods depending on the requirements. In this article, we will learn how to convert a string to a list of characters in Java.Example:In this example, we will use the toCharArray() method to convert a String into a character
    3 min read
    Convert List of Characters to String in Java
    Given a list of characters. In this article, we will write a Java program to convert the given list to a string. Example of List-to-String ConversionInput : list = {'g', 'e', 'e', 'k', 's'} Output : "geeks" Input : list = {'a', 'b', 'c'} Output : "abc" Strings - Strings in Java are objects that are
    4 min read
    Javascript Program To Reverse Words In A Given String
    Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i"Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks"Input: s = "getting good at coding needs a lot of practice" Output: s = "pra
    4 min read
    Javascript Program to Modify a string by performing given shift operations
    Given a string S containing lowercase English alphabets, and a matrix shift[][] consisting of pairs of the form{direction, amount}, where the direction can be 0 (for left shift) or 1 (for right shift) and the amount is the number of indices by which the string S is required to be shifted. The task i
    3 min read
    JavaScript String Methods
    JavaScript strings are the sequence of characters. They are treated as Primitive data types. In JavaScript, strings are automatically converted to string objects when using string methods on them. This process is called auto-boxing. The following are methods that we can call on strings.slice() extra
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences