Skip to content
Advertisement

How to generate a new random string each time, in a given string text, a regex is satisfied?

I have splited the resulted text of a file, what I need to do is to rename the header of that file, so I have taken the first indice of the sp (the header) and for each word in this header, I want to replace them with a different random string. But I have the same random string for each satisfied regex.

var sp = reader.result.split("n");
var randomString = Math.random().toString(36).substr(5, 5)

for ( let i in sp ){      
      if (i == 0) {  
         sp[i] = sp[i].replace(regex, randomString)      
       }
    }

Advertisement

Answer

So you fetch that header text from your file and then you want to extract each word from it and then replace it with some random string. Here’s the code for it.

On a side note Math.random() is not good enough, you need the crypto API

function generateHash (length = null) {
  const array = new Uint8Array((length || 64) / 2)
  window.crypto.getRandomValues(array)
  return Array.from(array, dec => {
    return dec.toString(16).padStart(2, '0')
  }).join('')
}

const header = 'One word and another word'
const modified = header.split(' ').map(val => generateHash(12)).join(' ')
console.log(modified)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement