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);
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory