Spintax (Spin Syntax) with JavaScript

S
Published in: 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);
Published in: JavaScript

Looking for something? Find here!

Meet the Author

Web Geek, Google Developer Expert
A
Amit Agarwal

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. He is the developer of Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Get in touch