Adding a function for swapping cases to the prototype object of strings - JavaScript

In JavaScript, we can extend built-in data types by adding custom methods to their prototype objects. This allows us to create reusable functions that work with existing data types like strings, arrays, and objects.

In this tutorial, we'll create a custom swapCase() method for strings that swaps the case of each character - converting uppercase letters to lowercase and vice versa, while keeping non-alphabetic characters unchanged.

Understanding String Prototype Extension

When we add a method to String.prototype, it becomes available to all string instances. The this keyword inside the method refers to the string that called the method.

Implementation

Here's how to implement the swapCase() method:

const str = 'ThIS iS A CraZY StRInG';

String.prototype.swapCase = function(){
    let res = '';
    for(let i = 0; i < this.length; i++){
        if(this[i].toLowerCase() === this[i].toUpperCase()){
            res += this[i];
            continue;
        };
        if(this[i].toLowerCase() === this[i]){
            res += this[i].toUpperCase();
            continue;
        };
        res += this[i].toLowerCase();
    };
    return res;
};

console.log(str.swapCase());
tHis Is a cRAzy sTriNg

How It Works

The algorithm works by iterating through each character and applying these rules:

  1. Non-alphabetic characters: If toLowerCase() and toUpperCase() return the same result, the character is non-alphabetic (numbers, spaces, punctuation) and remains unchanged.
  2. Lowercase characters: If the character equals its lowercase version, convert it to uppercase.
  3. Uppercase characters: Otherwise, convert it to lowercase.

Testing with Different Inputs

// Test with mixed content
console.log('Hello World!'.swapCase());
console.log('JavaScript123'.swapCase());
console.log('MiXeD cAsE wItH 123 & symbols!'.swapCase());
hELLO wORLD!
jAVAsCRIPT123
mIxEd CaSe WiTh 123 & SYMBOLS!

Alternative Implementation

Here's a more concise version using array methods:

String.prototype.swapCaseAlt = function(){
    return this.split('').map(char => {
        if(char === char.toLowerCase() && char === char.toUpperCase()){
            return char; // Non-alphabetic
        }
        return char === char.toLowerCase() ? char.toUpperCase() : char.toLowerCase();
    }).join('');
};

console.log('Hello World!'.swapCaseAlt());
hELLO wORLD!

Key Points

  • Prototype extension makes methods available to all instances of that data type
  • The this keyword refers to the calling string object
  • Non-alphabetic characters are identified when their upper and lower case versions are identical
  • The method returns a new string without modifying the original

Conclusion

Adding custom methods to JavaScript's built-in prototypes allows you to extend functionality in a reusable way. The swapCase() method demonstrates how to manipulate string characters while preserving non-alphabetic content.

Updated on: 2026-03-15T23:18:59+05:30

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements