How to randomly pick and replace a value from a template-string's options-pattern?

Issue

Aim:extract sentences or paragraphs from the given syntax structure. Pick any random word/phrase between “{” & “}” separated by “|” and make one realistic output.

Input:

{Hi|Hello|Hola} @name, Good {Morning|Evening}. {I am|We are} very {glad|hapy) that you came here {to meet us.

Output1: Hi abc Good Morning, I am very glad that you came here to meet us.

Output2: Hola abc Good Evening, I am very happy that you came here to meet us.

Output3: Hello abc Good Morning, We are very glad that you came here to meet us.

function extract([beg, end]) {
  const matcher = new RegExp(`${beg}(.*?)${end}`,'gm');
  const normalise = (str) => str.slice(beg.length,end.length*-1);
  return function(str) {
      return str.match(matcher).map(normalise);
  }
}
var str = "{Hi|Hello|Hola} @name, Good {Morning|Evening}. {I am|We are} very {glad|hapy) that you came here {to meet us."
const stringExtractor = extract(['{','}']);
const stuffIneed = stringExtractor(str)
I have extract the words between {} in array and now trying to compare and replace them

Solution

One solution is by using regular expressions
Here is a code snippet

I isolated the {...} parts, then split them by |, used random and then replaced the original {...} part with the random element

let t = '{Hi|Hello|Hola} @name, Good {Morning|Evening}. {I am|We are} very {glad|hapy} that you came here to meet us.'
let matches = t.match(/{([A-Z ](\|*))*}/gi)

for (const match of matches) {
  let splt = match.replace('{', '').replace('}', '').split('|')
  t = t.replace(match, splt[Math.floor(Math.random() * splt.length)])
}

console.log(t)

Second approach using a method

let t = '{Hi|Hello|Hola} @name, Good {Morning|Evening}. {I am|We are} very {glad|hapy} that you came here to meet us.'

function printSentence(sentence) {
 let matches = t.match(/{([A-Z ](\|*))*}/gi)

  for (const match of matches) {
    let splt = match.replace('{', '').replace('}', '').split('|')
    sentence = sentence.replace(match, splt[Math.floor(Math.random() * splt.length)])
  }

  console.log(sentence)
}


printSentence(t)
printSentence(t)
printSentence(t)

Answered By – Apostolos

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published