Skip to content

Instantly share code, notes, and snippets.

@alexgb
Last active December 14, 2015 03:29
Show Gist options
  • Save alexgb/5021506 to your computer and use it in GitHub Desktop.
Save alexgb/5021506 to your computer and use it in GitHub Desktop.
Because The New Yorker does it...
(function() {
var words = [
"Boötes",
"Brontë",
"caïquejee",
"Chloë",
"continuüm",
"coöperate",
"coöperation",
"coöperating",
"coöperative",
"coöpt",
"coördinate",
"coördinated",
"coördinating",
"coördination",
"coördinator",
"coördinators",
"Creüsa",
"daïs",
"faïence",
"langue d'oïl",
"naïf",
"naïve",
"naïveté",
"Noël",
"noöne",
"oöcyte",
"oölogy",
"preëminent",
"preëminently",
"preëmpt",
"preëmption",
"preëmptive",
"reëlect",
"reëlected",
"reëlecting",
"reënter",
"reëntered",
"reëntering",
"reëstablish",
"reëstablished",
"reëstablishing",
"zoölogy"
];
var diacriticsMap = {
"ä": "a",
"ë": "e",
"ï": "i",
"ö": "o",
"ü": "u"
};
function forEachDiacritic(fn) {
for(var diacritic in diacriticsMap) {
if (diacriticsMap.hasOwnProperty(diacritic)) {
fn(diacritic, diacriticsMap[diacritic]);
}
}
}
function removeDiacritics(text) {
forEachDiacritic(function(diacritic, equivalent) {
text = text.replace(new RegExp(diacritic, 'g'), equivalent);
});
return text;
}
// gets fancy so that we can preserve word capitalization
function addDiacritics(text) {
for (var i = 0; i < words.length; i++) {
var diacriticWord = words[i],
plainWord = removeDiacritics(diacriticWord);
text = text.replace(new RegExp(plainWord, 'gi'), function(match) {
forEachDiacritic(function(diacritic, equivalent) {
var regex = new RegExp(diacritic, 'g');
while ((charMatch = regex.exec(diacriticWord)) !== null) {
match = match.substr(0, charMatch.index) + diacritic + match.substr(charMatch.index + diacritic.length);
}
});
return match;
});
}
return text;
}
function forAllTextNodes(fn, element) {
element = element || document.body;
var nodes = element.childNodes;
for (var n = 0; n < nodes.length; n++) {
if (nodes[n].nodeType === Node.TEXT_NODE) {
fn(nodes[n]);
} else {
forAllTextNodes(fn, nodes[n]);
}
}
}
forAllTextNodes(function(node) {
node.textContent = addDiacritics(node.textContent)
});
})();
@alexgb
Copy link
Author

alexgb commented Feb 24, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment