Randomize variables in a string in javascript

using pipe and square brakets

Published on Oct 21, 2016

Reading time: 1 minutes.


Challenge

I have a string that looks like:

[Hi|Hello|Hey] ${user.name}! Would you like to [go for a walk|to the park]?

I need to render the text randomising the action (go for a walk or to the park) so that the message looks slightly different every time that is sent. Each block of square brackets could contain N variables (eg. [walk|run|swim|play tennis]) and each message can contain multiple blocks of random substrings.

I wrote a little snippet to do it, so feel free to use it:

{% gist andreafalzetti/2d90bc57dcdcaf1fde4dedd9361f1f93 %}

GitHub Gist available here.

Output Example:

  • Hello, Andrea! Would you like to go to the park?
  • Hi Andrea! Would you like to go for a walk?
  • Hello Andrea! Would you like to go for a walk?
  • Hey Andrea! Would you like to go to the park?