From 9c77b341380a306c337b5c55d5deea87815fe776 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Sun, 15 Nov 2020 13:09:03 +0200 Subject: [PATCH] Add swapCase --- snippets/swapCase.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 snippets/swapCase.md diff --git a/snippets/swapCase.md b/snippets/swapCase.md new file mode 100644 index 000000000..21985c0b9 --- /dev/null +++ b/snippets/swapCase.md @@ -0,0 +1,22 @@ +--- +title: swapCase +tags: string,beginner +--- + +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`. + +```js +const swapCase = str => + [...str] + .map(c => (c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase())) + .join(''); +``` + +```js +swapCase('Hello world!'); // 'hELLO WORLD!' +```