Skip to content

Instantly share code, notes, and snippets.

@irazasyed
Created April 14, 2013 12:06
Show Gist options
  • Save irazasyed/5382470 to your computer and use it in GitHub Desktop.
Save irazasyed/5382470 to your computer and use it in GitHub Desktop.
JavaScript: Text Spinner Function
/* ============================================================
| :=Text Spinner
=============================================================== */
function preg_quote(str, delimiter) {
return (str + '').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&');
}
function spin(text) {
var matches = text.match(/{[^<]+/gi);
if (matches === null) {
return text;
}
if (matches[0].indexOf('{') != -1) {
matches[0] = matches[0].substr(matches[0].indexOf('{') + 1);
}
if (matches[0].indexOf('}') != -1) {
matches[0] = matches[0].substr(0, matches[0].indexOf('}'));
}
var parts = matches[0].split('|');
var t = preg_quote(matches[0]);
e_v = new RegExp('{' + t + '}', 'g');
text = text.replace(e_v, parts[Math.floor(Math.random()*parts.length)]);
return spin(text);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment