Skip to content

Instantly share code, notes, and snippets.

@alex-kinokon
Last active August 29, 2015 14:22
Show Gist options
  • Save alex-kinokon/edfb0917e9d274bd0e68 to your computer and use it in GitHub Desktop.
Save alex-kinokon/edfb0917e9d274bd0e68 to your computer and use it in GitHub Desktop.
curly.js
/* curly.js applies smart quotes (curly) to web pages that does not use it.
* (C) 2015 Alex Mattrick. CC0 Public Domain Dedication.
*/
var curlyquote = (function() {
// Elements with these tags will be ignored.
var ignoredTags = ['INPUT', 'PRE', 'CODE', 'SELECT', 'TEXTAREA', 'NOSCRIPT', 'SCRIPT'];
// Elements with these tags will NOT be considered a separate sentence.
var continuous = ['STRONG', 'EM', 'B', 'I', 'U', 'A', 'STRIKE', 'SPAN'];
// Create a local copy for undefined in case overwritten.
var undefined;
var curlyquote = function curlyquote(element, continuity) {
if (ignoredTags.indexOf(element.tagName) > -1) {
return true;
} else if (element.childNodes && element.childNodes.length) {
// inheritant is the name for the variable continuity for childNodes.
var child, inheritant = false, i = 0;
while (child = element.childNodes[i++]) {
curlyquote(child, inheritant);
inheritant = (child.tagName === undefined || continuous.indexOf(child.tagName) > -1);
}
} else if (element.nodeValue) {
try {
if (continuity) {
// Adds a random temporary letter to the beginnig so smartypants won't consider
// it as a separate sentence.
element.nodeValue = curlyquote.smartypants('s' + element.nodeValue).slice(1);
} else {
element.nodeValue = curlyquote.smartypants(element.nodeValue);
}
} catch (e) {
// Nothing happens.
}
}
};
curlyquote.smartypants = function (text) {
return text
.replace(/---/g, '\u2014')
.replace(/--/g, '\u2013')
.replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018') // ‘ LEFT SINGLE
.replace(/'/g, '\u2019') // ’ RIGHT SINGLE
.replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c') // “ LEFT DOUBLE
.replace(/"/g, '\u201d') // ” RIGHT DOUBLE
.replace(/\.{3}/g, '\u2026');
};
return curlyquote;
})();
curlyquote(document.body);
document.title = curlyquote.smartypants(document.title);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment