-1

Let's say I have a string like this:

This is just a test {#3,2,7,9} this is another test {#21,2,11}

How can I retrieve all instances of {#x,y,..} and replace it with a random number it contains?

For example, the string above could become:

This is just a test 2 this is another test 11
  • 1
    What have you tried? (hint: [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) and [replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) with a _replacerFunction_) – Paul S. Jan 02 '22 at 11:25
  • @PaulS. I don't know what to do and not sure what to search either. If it was just one instance, I could do it but there could be an infinite number of instances all with varying amount of integers inside of them – oiejfwijoewf Jan 02 '22 at 11:26
  • If you're learning this for the first time, I'd reccomend that you try to do the following things: 1, try writing some code which uses a RegExp to find all instances of a fixed-length pattern in a string, the pattern should happen multiple times. 2, try writing some code which uses a RegExp to find a pattern which is of varying length. Combine 1 and 2 and you've got your matcher. 3. Write a function which given a string `"x,y,z,..."` chooses a random item from the list. Combine this as the replacerFunction with the matcher from 1 and 2 and you've now got your solution – Paul S. Jan 02 '22 at 11:33

2 Answers2

1

Try using replace() method

Regex Demo

https://regex101.com/r/s3O59z/1

let string = 'This is just a test {#3,2,7,9} this is another test {#21,2,11}'

let result = string.replace(/{#(.*?)}/g, (match, p1) => {
  let nums = p1.split(',')
  return nums[Math.floor(Math.random() * nums.length)]
})

console.log(result)
User863
  • 19,346
  • 2
  • 17
  • 41
0

There are multiple ways to do this. The more modern way is to use a template literal, To retrieve a random value from a given Array you can create a small helper method. Something like:

const randomValue = arr => arr[Math.floor(Math.random() * arr.length)];

const testing = `This is just a test ${
  randomValue([3,2,7,9,112,18,37,12])} this is another test ${
  randomValue([21,2,11,98,22,1200,7,24])}`;

[...Array(5)].forEach( v => {
  console.log( `This is just a test ${
    randomValue([3,2,7,9,112,18,37,12])} / this is another test ${
    randomValue([21,2,11,98,22,1200,7,24])}`);
});
//console.log(testing);
KooiInc
  • 119,216
  • 31
  • 141
  • 177