Design & Download
Your JS Library
in Seconds!!!

Snippet: swapCase()

Written by Christopher West (cwest) on November 22, 2015.
Change the case of every character either from upper to lower or lower to upper.
function swapCase(s) {
  var l = s.toLowerCase(), u = s.toUpperCase(), lc, uc;
  return s.replace(/\S/g, function(m, i) {
    lc = l.charAt(i);
    uc = u.charAt(i);
    return lc != m ? uc == m ? lc : m : uc;
  });
}

Python provides a way to change the casing of all of the characters in a string so JavaScript should be able to as well, right?

console.log(YourJS.swapCase("Hello World!!!"));
// > "hELLO wORLD!!!"

swapCase(...) API Documentation

Description

Turns all lowercased characters into uppercased characters and vice-versa.

Parameters

  1. s {string}:
    The string to be duplicated and returned with all characters having the opposite casing.

Returns

Returns a copy of s with all lowercased character as uppercased characters and all uppercased characters as lowercased characters.