Randomize variables in a string in javascript

using pipe and square brakets

Posted by Andrea Falzetti on October 21, 2016

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:

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?

Share this:



comments powered by Disqus