Home > Web Front-end > JS Tutorial > body text

Reverse the case of a string - Javascript

Mary-Kate Olsen
Release: 2024-10-04 18:19:31
Original
806 people have browsed it

Reverse the case of a string - Javascript

Write a function that takes a string and reverses the case of all its letters.

Solution


function reverseStringCase(text) {
  let reversedString = [];

  for (let i = 0; i < text.length; i++) {
    if (text[i] == text[i].toUpperCase()) {
      reversedString.push(text[i].toLowerCase());
    } else {
      reversedString.push(text[i].toUpperCase());
    }
  }

  console.log(reversedString.join(""));
  return reversedString.join("");
}

// Another solution for reversing string cases

function reverseStringCases(text) {
  const reversedString = text
    .split("")
    .map((item) =>
      item === item.toUpperCase() ? item.toLowerCase() : item.toUpperCase()
    )
    .join("");

  console.log(reversedString);
  return reversedString;
}

reverseStringCase(
  "L'âme nE se dÉvelopPe pAs sAnS ChAngEmenT, eT leS DoUtes Sont EsSentIels à la crOisSanCe."
);

reverseStringCases(
  "L'âme nE se dÉvelopPe pAs sAnS ChAngEmenT, eT leS DoUtes Sont EsSentIels à la crOisSanCe."
);


Copy after login

Result


l'ÂME Ne SE DéVELOPpE PaS SaNs cHaNGeMENt, Et LEs dOuTES sONT eSsENTiELS À LA CRoISsANcE.

l'ÂME Ne SE DéVELOPpE PaS SaNs cHaNGeMENt, Et LEs dOuTES sONT eSsENTiELS À LA CRoISsANcE.


Copy after login

The above is the detailed content of Reverse the case of a string - Javascript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template