Skip to content

Instantly share code, notes, and snippets.

@georgebrata
Created May 30, 2016 08:45
Show Gist options
  • Save georgebrata/23d2f7484d8544ae17972106ef8a5891 to your computer and use it in GitHub Desktop.
Save georgebrata/23d2f7484d8544ae17972106ef8a5891 to your computer and use it in GitHub Desktop.
Vanilla Javascript Spintax Function
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Spintax Spinner</title>
</head>
<body>
<script>
var SPINTAX_PATTERN = /\{[^"\r\n\}]*\}/;
var spin = function (spun) {
var match;
while (match = spun.match(SPINTAX_PATTERN)) {
match = match[0];
var candidates = match.substring(1, match.length - 1).split("|");
spun = spun.replace(match, candidates[Math.floor(Math.random() * candidates.length)])
}
return spun;
}
var sample_str="{Hey|Hello} {there|mate}, {how are you|what's up}?";
alert(spin(sample_str)); /* spin(sample_str) is your parsed text */
//credits to http://www.thedeveloper24.com/
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment