Skip to content

Instantly share code, notes, and snippets.

@ievans3024
Last active September 12, 2023 19:55
Show Gist options
  • Select an option

  • Save ievans3024/0a4e8767c28df8804365a529ab815596 to your computer and use it in GitHub Desktop.

Select an option

Save ievans3024/0a4e8767c28df8804365a529ab815596 to your computer and use it in GitHub Desktop.
Hack to add .toSarcasm() method to javascript strings
/*
* A common way of denoting sarcasm in text on the internet is to alternate upper and lower casing in the text.
* For example: "But I didn't do it!" might become "BuT i DiDn'T dO iT!"
*
* This adds a method to strings in JavaScript to convert them to this sarcastic format.
*
* The method returns a new string with the casing of each letter appropriately changed.
* The method supports letters with diacritic marks, e.g., umlauts.
*
* By default, it will start the converted string in lowercase form
* e.g., "My feelings are hurt!".toSarcasm() -> "mY fEeLiNgS aRe HuRt!"
*
* Initial case can be preserved by passing in true:
* e.g., "My feelings are hurt!".toSarcasm(true) -> "My FeElInGs ArE hUrT!"
*/
Object.defineProperty(
String.prototype,
'toSarcasm',
{
value(preserveInitialCase = false) {
const alphaRegex = /^[\p{Letter}\p{Mark}]$/u;
let capitalize = false;
let output = '';
if (this.length) {
if (preserveInitialCase) {
capitalize = this[0] !== this[0].toLowerCase() && this[0] === this[0].toUpperCase();
}
for (const char of this) {
if (alphaRegex.test(char)) {
output += (capitalize ? char.toUpperCase() : char.toLowerCase());
capitalize = !capitalize;
} else {
output += char;
}
}
}
return output;
},
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment