Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

160
Visualizações
How to retrieve a substring and replace it with a random value it contains?

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
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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)

about 4 years ago · Juan Pablo Isaza Relatório

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);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda