Created
May 30, 2016 08:45
-
-
Save georgebrata/23d2f7484d8544ae17972106ef8a5891 to your computer and use it in GitHub Desktop.
Vanilla Javascript Spintax Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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