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
>Solution :
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)