Spintax (Spin Syntax) with JavaScript

Spintax, short for spin syntax, is a list of text phrases, sentences, and synonyms separated by the pipe (|) character. Each group of keywords is enclosed inside curly ({}) brackets.

The Spintax parser picks a random keyword or sentence from the available choices and generates a unique sentence for each iteration. For instance, if the spintax is {Hello|Hi|Hola}, the output may contain either of these greetings.

Spintax can be nested as well like {{Thanks and|Best}Regards|Cheers}. Here’s a spintax parser written in JavaScript.


var text = "{{Hello|Hi|Hola}, How {have you been|are you doing}? " +
           "Take care. {{Thanks and|Best} Regards|Cheers|Thanks}";

var matches, options, random;

var regEx = new RegExp(/{([^{}]+?)}/);

while((matches = regEx.exec(text)) !== null) {
  options = matches[1].split("|");
  random = Math.floor(Math.random() * options.length);
  text = text.replace(matches[0], options[random]);
}

console.log(text);