w3resource

JavaScript: Input a string and converts upper case letters to lower and vice versa

JavaScript String: Exercise-10 with Solution

Write a JavaScript function that takes a string with both lowercase and upper case letters as a parameter. It converts upper case letters to lower case, and lower case letters to upper case.

Test Data:
console.log(swapcase('AaBbc'));
"aAbBC"

Visual Presentation:

JavaScript: Input a string and converts upper case letters to lower and vice versa

Sample Solution:

JavaScript Code:

// Define a function named swapcase that takes a string str as input
swapcase = function swapcase(str) {
    // Use the replace method with a regular expression to match lowercase and uppercase letters separately
    return str.replace(/([a-z]+)|([A-Z]+)/g, function(match, chr) {
        // For each match, if chr (lowercase letter) exists, convert it to uppercase; otherwise, convert the match (uppercase letter) to lowercase
        return chr ? match.toUpperCase() : match.toLowerCase();
    });
}
// Output the result of applying the swapcase function to the string 'AaBbc'
console.log(swapcase('AaBbc'));

Output:

aAbBC

Explanation:

In the exercise above,

  • The function "swapcase()" is declared, taking a string 'str' as input.
  • Inside the function, a regular expression is used to match lowercase and uppercase letters separately.
  • The "replace()" method is applied to the string 'str', replacing each match:
    • If the match is a lowercase letter ('([a-z]+)'), it is replaced with its uppercase equivalent.
    • If the match is an uppercase letter ('([A-Z]+)'), it is replaced with its lowercase equivalent.
  • The modified string is returned by the function.
  • Finally, the console.log statement calls the "swapcase()" function with the string 'AaBbc' as input and outputs the result.

Flowchart:

Flowchart: JavaScript- Input a string  and converts upper case letters to lower and vice versa

Live Demo:

See the Pen JavaScript Input a string and converts upper case letters to lower and vice versa - string-ex-10 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to capitalize the first letter of each word in a string.
Next: Write a JavaScript function to convert a string into camel case.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-string-exercise-10.php