30秒学会 JavaScript 片段 · 2023年11月9日

30秒学会 JavaScript 片段 – Swapcase string

Creates a string with uppercase characters converted to lowercase and vice versa.

  • Use the spread operator (...) to convert str into an array of characters.
  • Use String.prototype.toLowerCase() and String.prototype.toUpperCase() to convert lowercase characters to uppercase and vice versa.
  • Use Array.prototype.map() to apply the transformation to each character, Array.prototype.join() to combine back into a string.
  • Note that it is not necessarily true that swapCase(swapCase(str)) === str.

代码实现

const swapCase = str =>
  [...str]
    .map(c => (c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase()))
    .join('');

swapCase('Hello world!'); // 'hELLO WORLD!'

翻译自:https://www.30secondsofcode.org/js/s/swap-case